1

I would like to know how to change array of objects with array of values in JavaScript. I have array arr and nested object nestobj, want to place arr values in nested object value


var arr =["xyz", "abc", "3", "str"];
var nestobj=[
  {field1: '' },
  {field2: '' },
  {field3: '' }
]


var result = nestobj.map(e=>{
   arr.map(i=>{
     e:i
  })
})

Expected Output

[
  {field1: 'xyz' },
  {field2: 'abc' },
  {field3: '3' }
]

2 Answers 2

1

You can use Array#map with Object.keys.

var arr =["xyz", "abc", "3", "str"];
var nestobj=[
  {field1: '' },
  {field2: '' },
  {field3: '' }
]
let res = nestobj.map((x, i)=>({[Object.keys(x)[0]]: arr[i]}));
console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

0

nestobj.map((element, index) => {
  element[`field${index+1}`] = arr[index];
});

Comments

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.