2014-12-04 67 views
0

我有兩個本地JSON文件。我想將一個對象的屬性從一個文件添加到另一個文件中的對應對象。將對象屬性從一個JSON數據文件添加到另一個

下面是一個例子..

數組1:

[ 
    { 
    "id": 1, 
    "username": "Joe Smith", 
    "pic": "images/profile/Joe_smith.jpg" 
    }, 
    { 
    "id": 2, 
    "username": "Jane Smith", 
    "pic": "images/profile/Jane_smith.jpg" 
    } 
] 

數組2:

[ 
{ 
    "id": 3, 
    "userId": 1, 
    "profession": "dentist" 
}, 
{ 
    "id": 4, 
    "userId": 2, 
    "profession": "pilot" 
} 

的想法是在array1添加 「PIC」 屬性來ARRAY2正確的對象。如果Array1中的id與Array2中的userId匹配,則它是正確的匹配。 Array2最終會看起來像這樣:

[ 
{ 
    "id": 3, 
    "userId": 1, 
    "profession": "dentist", 
    "pic": "images/profile/Joe_smith.jpg" 
}, 
{ 
    "id": 4, 
    "userId": 2, 
    "profession": "pilot", 
    "pic": "images/profile/Jane_smith.jpg" 
} 

之後我將使用angular來顯示臉部名稱。希望我解釋說好的。任何幫助將非常感激!

+0

看起來像解析JSON一樣簡單,遍歷兩個數組併合並單個對象。特別是你有什麼問題嗎?你知道如何解析JSON嗎?如何遍歷數組? – 2014-12-04 22:46:10

+0

我知道如何迭代數組,在這種情況下,我可能需要這樣做兩次。解析的東西雖然對我來說是新的。 – user3802738 2014-12-04 22:59:01

+0

[在JavaScript中解析JSON?](http://stackoverflow.com/q/4935632/218196) – 2014-12-04 23:10:32

回答

0

只是爲了它的樂趣。在這個例子中使用https://lodash.com

var people = [ 
    { "id": 1, "username": "Joe Smith", "pic": "images/profile/Joe_smith.jpg" }, 
    { "id": 2, "username": "Jane Smith", "pic": "images/profile/Jane_smith.jpg"}, 
    { "id": 3, "username": "I play too much games", "pic": "images/profile/toomuch.jpg"} 
]; 

var professions = [ 
    { "id": 3, "userId": 1, "profession": "dentist" }, 
    { "id": 4, "userId": 2, "profession": "pilot" } 
]; 

var workers = _.map(people, function(human) { 
    var work = _.findWhere(professions, { 'userId': human.id }); 
    return _.extend(human, work ? work : { 'profession' : 'unemployed' }); 
}); 

console.log(workers); 
相關問題