How to create new object by the array of objects and array of values in JavaScript

Viewed 38

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

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);

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

Related