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?

6
  • 1
    You need data[i][property[j]] = ""; Commented Jul 8, 2021 at 5:30
  • Or do: data.forEach(person => property.forEach(prop => person[prop] = "")); Commented Jul 8, 2021 at 5:33
  • 1
    Does this answer your question? Add a property to a JavaScript object using a variable as the name? Commented Jul 8, 2021 at 5:35
  • the link which you provided is different from the question posted Commented Jul 8, 2021 at 5:36
  • With .property you are checking for 'property' key in each object. Hence, the undefined. Commented Jul 8, 2021 at 5:45

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.