简体   繁体   English

如何在javascript中向数组添加新对象(键值对)?

[英]How to add a new object (key-value pair) to an array in javascript?

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}

使用.push

items.push({'id':5});

.push() will add elements to the end of an array. .push()会将元素添加到数组的末尾。

Use .unshift() if need to add some element to the beginning of array ie:如果需要在数组的开头添加一些元素,请使用.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 ie:如果您想在特定索引处添加对象,请使用.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);

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, newArray will return 5 (the length of the array).在这种情况下, newArray将返回 5(数组的长度)。

newArray = items.concat({'id': 5})

However, here newArray will return [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}].但是,这里newArray将返回 [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}]。

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}];

If you're doing jQuery, and you've got a serializeArray thing 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"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM