2016-03-22 26 views
0

我知道如何從json數組中刪除項目,但似乎無法在添加時使其工作。使用名稱/值從json數組中添加項目

數組:

var users = [ 
{name: 'james', id: '1'} 
] 

要添加,使其成爲:

var users = [ 
    {name: 'james', id: '1'}, 
    {name: 'thomas', id: '2'} 
    ] 

下面的代碼去除數組:

Array.prototype.removeValue = function(name, value){ 
     var array = $.map(this, function(v,i){ 
     return v[name] === value ? null : v; 
    }); 
    this.length = 0; //clear original array 
    this.push.apply(this, array); //push all elements except the one we want to delete 
    } 

    removeValue('name', value); 
//space removed 

我需要什麼樣的變化,使反向爲數組添加值?

+0

不要將JSON(文本數據交換符號)與原生JavaScript數組混淆。你所問的與JSON有很多關係,因爲貓與檸檬有關。另外,你的'removeValue'似乎適用於對象數組,而不是任意數組。鑑於此,請詳細說明您希望如何按「名稱/值」添加項目。 –

+0

不當使用術語和語法的道歉。我想要的基本上是相反的(添加而不是刪除):http://stackoverflow.com/questions/6310623/remove-item-from-json-array-using-its-name-value – Juan

+0

所以你想' addValue('name',value);'到底是什麼?添加一個新的對象到數組?更新數組中的所有對象?如果只是提供一個輸入和預期輸出的例子,那麼我們將更容易幫助你。您發佈的代碼與您的問題幾乎無關。 –

回答

0

With Array.prototype.push()

var sports = ["plongée", "baseball"]; 
var total = sports.push("football", "tennis"); 

console.log(sports); // ["plongée", "baseball", "football", "tennis"] 
console.log(total); // 4 
0

我覺得更擬合函數是filtermap

Array.prototype.removeValue = function(name, value){ 
    var array = $.filter(this, function(v,i){ 
     return v[name] !== value; 
    }); 
    this.length = 0; //clear original array 
    this.push.apply(this, array); //push all elements except the one we want to delete 
} 

我只是假設長度和推黑客工作,因爲我從來沒有用過他們自己。

+0

這不是問題所在。 OP想要**添加**到陣列中。他們只發布代碼以表明他們知道如何刪除某些內容(即使它完全不相關)。 –

相關問題