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' }
]
Heretic Monkey
12.2k7 gold badges63 silver badges133 bronze badges
asked Jul 15, 2021 at 14:25

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

answered Jul 15, 2021 at 14:33
Sign up to request clarification or add additional context in comments.

Comments

0

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

answered Jul 15, 2021 at 14:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.