How to add new a new property to an object in an array?
This question already has an answer here:
Easiest way to append is either use:
fruits[0]["taste"] = "good";
or:
fruits[0].taste = "good";
I add an taste
element to each object, and fill it with the value "good"+ index of the element
. Here is a simple demo:
var fruits = [];
fruits[0] = {name:"apple", stock:"1box"};
fruits[1] = {name:"banana", stock:"2box"};
fruits[2] = {name:"banana", stock:"3box"};
for(var index=0;index<fruits.length;index++){
fruits[index].taste="good "+index;
}
console.log(fruits);
The easiest way to add a property to existing object for each element in array is to itterate over the array and set the property to the desired value using
element[index].desiredProperty = desiredValue;
For example see following fiddle: https://jsfiddle.net/to70xe4j/1/
链接地址: http://www.djcxy.com/p/17952.html上一篇: 我怎样才能将两个数组组合成一个数组在JavaScript中?
下一篇: 如何将新的属性添加到数组中的对象?