Reputation: 27
I have the below array of objects
const data=[{"id":1,"name":"Sam"},{"id":2,"name":"Peter"},{"id":3,"name":"Tom"}]
I have another array with property names
const property=["Address","Contact No."]
I want to create this property with value empty in the existing array so that the output will be as below
[{"id":1,"name":"Sam","Address":"","Contact No.":""},{"id":2,"name":"Peter","Address":"","Contact No.":""},{"id":3,"name":"Tom","Address":"","Contact No.":""}]
I tried the below code
for(var i=0;i<data.length;i++)
{
for(var j=0;j<property.length;j++)
{
data[i].property[j]=""
}
}
Am getting error as cannot set property '0' of undefined. Can someone let me know how to achieve this?
Upvotes: 0
Views: 459
Reputation: 950
const data=[{"id":1,"name":"Sam"},{"id":2,"name":"Peter"},{"id":3,"name":"Tom"}]
const property=["Address","Contact No."]
property.forEach((prop)=> {
data.forEach((d) => {
d[prop] = ""
})
})
console.log(data)
Upvotes: 1