简体   繁体   中英

Create a new property from an array with null value in an array of objects in javascript

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?

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)

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.

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