I have the below JSON array,
const data = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]
and I have to insert one more property to each object, and expected result would be like this.
const data = [{id:1,name:'a',selected:false},{id:2,name:'b',selected:false},{id:3,name:'c',selected:false}]
I'm trying to achieve this javascript only.
Please help me on this.
The question did not reach the standards of Stackoverflow, but from your comments, I believe that you are seriously looking for a solution's than your reputation.
The answer is kind of simple old-school method, please refer and give a try. Thanks.
const data = [{id:1,name:'a',selected:false},{id:2,name:'b',selected:false},{id:3,name:'c',selected:false}] data.forEach((element,index) => { element["selected"] = false, element["test"]=index+1 // any key-value pairs }); console.log(data)
A simple loop is all you need.
for (let item of data) {
item.selected = false;
}
On each iteration of this loop, item
becomes the next item from the iterated object ( data
, in this case). Since the array still references these same objects, you can modify item
, and this modification also appears on the item in data
... again because it is the same object.
var data = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];
for (i = 0; i < data.length; i++) {
// add the addition property using dot notation
data[i].selected = 'false';
}
// output to console the updated data
console.log(data);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.