0

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?

kameswari
  • 27
  • 5
  • 1
    You need `data[i][property[j]] = "";` –  Jul 08 '21 at 05:30
  • Or do: `data.forEach(person => property.forEach(prop => person[prop] = ""));` –  Jul 08 '21 at 05:33
  • 1
    Does this answer your question? [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) –  Jul 08 '21 at 05:35
  • the link which you provided is different from the question posted – kameswari Jul 08 '21 at 05:36
  • With .property you are checking for 'property' key in each object. Hence, the undefined. – Tushar Shahi Jul 08 '21 at 05:45
  • It doesn't have to be a 100% duplicate. However it really is, because the fact that you are populating an array with properties stored in an array is incidental. The key concept is using a key that is stored in a variable, and that's 100% answered by the other question. It's even about *adding a property*, not just accessing it, making it a 110% percent duplicate. –  Jul 08 '21 at 05:54

1 Answers1

1
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)
Harrys Kavan
  • 741
  • 9
  • 28
  • The question was marked as dupe 7 minutes already when you posted this. Please don't post answers to dupes unless the dupe isn't an actual dupe or really obsolete. –  Jul 08 '21 at 05:56