-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
  • 10,875
  • 2
  • 13
  • 37
smijith
  • 53
  • 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
  • 35,416
  • 5
  • 56
  • 100
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
  • 10,875
  • 2
  • 13
  • 37
-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
  • 246,420
  • 52
  • 367
  • 373