Home > OS >  inserting the elements of a list into an object
inserting the elements of a list into an object

Time:02-04

I have a list. Like this;

0: {value: 50, key: 'A'}
1: {value: 10, key: 'B'}
2: {value: 15, key: 'C'}
3: {value: 20, key: 'D'}
4: {value: 25, key: 'E'}

I want to convert this list into an object.
for example; the output should be like this:

let data = [{     
   A: 50, 
   B: 10, 
   C: 15, 
   D: 20, 
   E: 25 
}]

I need to handle this issue on the javascript side, but because I am not familiar with javascript, the solutions I found did not work, I usually always output this way.

[ { A:50 }, { B: 10 }, { C: 15 } { D: 20 }, { E: 25 } ]

CodePudding user response:

You can use Object.fromEntries after converting the array to an array of key-value pairs with Array#map.

let arr = [{value: 50, key: 'A'},{value: 10, key: 'B'},{value: 15, key: 'C'},{value: 20, key: 'D'},{value: 25, key: 'E'}];
let res = Object.fromEntries(arr.map(x => [x.key, x.value]));
console.log(res);

CodePudding user response:

You can convert an array into an object using the reduce method:

const x = [
  {value: 50, key: 'A'},
  {value: 10, key: 'B'},
  {value: 15, key: 'C'},
  {value: 20, key: 'D'},
  {value: 25, key: 'E'}
]

function convert(arr) {
  return arr.reduce((acc, item) => {
    acc[item.key] = item.value;
    return acc;
  }, {})
}

console.log(convert(x))

  • Related