-3

This is my array format

let array = [ 0: { key:"name", value: "John" }, 1: { key:"age", value:25 }, 2: { key:"job", value:"software engineer" },... ]; 

Change this array to object in given below format

{ name: "John", age: 27, job: "software engineer" } 
0

3 Answers 3

1

You can achieve it using forEach on the array.

Give this a try:

const array = [{ key: "name", value: "John" }, { key: "age", value: 25 }, { key: "job", value: "software engineer" }]; const expected = {}; array.forEach(item => expected[item.key] = item.value); console.log(expected);

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

Comments

0

You can use Array.prototype.reduce() to do this:

let array = [ { key:"name", value: "John" }, { key:"age", value:25 }, { key:"job", value:"software engineer" } ]; let result = array.reduce((a,b) => { a[b.key] = b.value; return a; }, {}); console.log(result);

Comments

-1

All you need to do is to loop over the array using forEach, for loop, while loop etcand push the values in a new object.

Also make sure that your array syntax is correct because the way you have mentioned it in the question is incorrect.

const data = [{ key:"name", value: "John" },{ key:"age", value:25 },{ key:"job", value:"software engineer" } ]; const res = {}; data.forEach(item => { res[item.key] = item.value}); console.log(res);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.