-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" 
}
Cuong Le Ngoc
  • 11,595
  • 2
  • 17
  • 39
smijith
  • 13
  • 7

3 Answers3

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);
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
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);
Cuong Le Ngoc
  • 11,595
  • 2
  • 17
  • 39
-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);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400