javascript 如何在javascript中将新对象(键值对)添加到数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18954777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a new object (key-value pair) to an array in javascript?
提问by exAres
I have an array as :
我有一个数组:
items=[{'id':1},{'id':2},{'id':3},{'id':4}];
How should I add a new pair {'id':5}
to the array?
我应该如何{'id':5}
向数组中添加一个新对?
回答by Mohammad Usman
.push()will add elements to the end of an array.
.push()会将元素添加到数组的末尾。
Use .unshift()if need to add some element to the beginning of array i.e:
如果需要在数组的开头添加一些元素,请使用.unshift(),即:
items.unshift({'id':5});
Demo:
演示:
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.unshift({'id': 0});
console.log(items);
And use .splice()in case you want to add object at a particular index i.e:
如果您想在特定索引处添加对象,请使用.splice(),即:
items.splice(2, 0, {'id':5});
// ^ Given object will be placed at index 2...
Demo:
演示:
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.splice(2, 0, {'id': 2.5});
console.log(items);
回答by Natorious
Sometimes .concat()is better than .push()since .concat()returns the new array whereas .push()returns the length of the array.
有时.concat()比.push()更好,因为.concat()返回新数组而.push()返回数组的长度。
Therefore, if you are setting a variable equal to the result, use .concat().
因此,如果您设置的变量等于结果,请使用.concat()。
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
newArray = items.push({'id':5})
In this case, newArraywill return 5 (the length of the array).
在这种情况下,newArray将返回 5(数组的长度)。
newArray = items.concat({'id': 5})
However, here newArraywill return [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}].
但是,这里newArray将返回 [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}]。
回答by anoraq
If you're doing jQuery, and you've got a serializeArraything going on concerning your form data, such as :
如果您正在使用 jQuery,并且您有一个关于表单数据的serializeArray事情,例如:
var postData = $('#yourform').serializeArray();
// postData (array with objects) :
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, etc]
...and you need to add a key/value to this array with the same structure, for instance when posting to a PHP ajax request then this :
...并且您需要向该数组添加一个具有相同结构的键/值,例如在发布到 PHP ajax 请求时,则:
postData.push({"name": "phone", "value": "1234-123456"});
Result:
结果:
// postData :
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, {"name":"phone","value":"1234-123456"}]
回答by U?ur
New solution with ES6
ES6 的新解决方案
Default object
默认对象
object = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
Another object
另一个对象
object = {'id': 5};
Object assign ES6
对象分配 ES6
resultObject = {...obj, ...newobj};
Result
结果
[{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}];