2010-12-04 122 views
1

我有javascript對象的像的數組以下:更新對象的陣列中的JavaScript

var food = [ 
    {id: 1, name: 'Apples', owned: true }, 
    {id: 2, name: 'Oranges', owned: false }, 
    {id: 3, name: 'Bananas', owned: true } 
]; 

然後我接收與下列數據的另一數組:

var newFood = [ 
    {id: 1, name: 'Peas'}, 
    {id: 2, name: 'Oranges'}, 
    {id: 3, name: 'Bananas'}, 
    {id: 4, name: 'Grapefruits'} 
]; 

如何更新的以前的food數組中有新的信息newFeed,沒有覆蓋原來的owned屬性,同時增加owned: false到任何新的對象?

請記住,這是純javascript,而不是jQuery。

回答

5

你可能想索引的食物通過ID,以便使食物的對象,而不是數組:

var food = { 
1: {name: "Apples", owned: true}, 
//... 
} 

然後遍歷newFood並適當更新的字段。

0

這工作:

var temp = {}; 

for (var i = 0, l = food.length; i < l; i += 1) { 
    temp[food[i].name] = true; 
} 

for (var i = 0, l = newFood.length; i < l; i += 1) { 
    if (!temp[newFood[i].name]) { 
     food.push({ id: food.length + 1, name: newFood[i].name, owned: false }); 
    } 
} 

第一for語句將填充temp對象從food陣列水果的名稱,讓我們知道哪些水果在它存在。在這種情況下,temp將是這樣的:

{ "Apples": true, "Oranges": true, "Bananas": true } 

然後,在newFood如果存在temp水果,而第二for語句檢查每種水果如果沒有,如果將一個新的數組項進入food數組。

0

有這樣的事嗎? JSFiddle Example

的JavaScript

function updateFood(newFood, oldFood) { 
    var foodLength = oldFood.length - 1; 
    for (var i = 0; i < newFood.length; i++) { 
     if (i > foodLength) { //add more if needed 
      newFood[i].owned = false; 
      oldFood.push(newFood[i]); 
     } else if (!food[i].owned) { //replace if needed 
      newFood[i].owned = false; 
      oldFood[i] = newFood[i]; 
     } 
    } 
} 
3

我認爲你可以使用underscore.js爲解決這個問題。

var arrayObj = [ 
       {Name:'John',LastName:'Smith'}, 
       {Name:'Peter',LastName:'Jordan'}, 
       {Name:'Mike',LastName:'Tyson'} 
       ]; 

var element = _.findWhere(arrayObj, { Name: 'Mike' }); 
element.Name="SuperMike"; 

console.log(arrayObj);