-3

It seems duplicated question, but I could not find ideal way to solve it. (I searched on google about the keyword like 'convert array of object'... Yes! I'm stupid...)

My current data is like this.

[ { name: 'apple', value: 'red' },
  { name: 'banana', value: 'yellow' },
  { name: 'ocean', value: 'blue'}
]

And, I want to change it to object like this.

[ { 'apple' : 'red' }, { 'banana' : 'yellow' }, { 'ocean' : 'blue' } ]

Thanks in advance!

Maker
  • 123
  • 1
  • 9

2 Answers2

2

You can use Array.prototype.map:

data.map(el => ({[el.name]: el.value}))

Example:

console.log([
  { name: 'apple', value: 'red' },
  { name: 'banana', value: 'yellow' },
  { name: 'ocean', value: 'blue'}
].map(el => ({[el.name]: el.value})));
jabaa
  • 5,844
  • 3
  • 9
  • 30
0

Use Array.prototype.reduce:

const result = data.reduce(
  (acc, el) => {
    acc[el.name] = el.value;
    return acc;
  },
  {}));

Usage

const data = [
  { name: 'apple', value: 'red' },
  { name: 'banana', value: 'yellow' },
  { name: 'ocean', value: 'blue'}
];

const result = data.reduce(
  (acc, el) => {
    acc[el.name] = el.value;
    return acc;
  },
  {}));

console.log(result);

Output:

Object { apple: "red", banana: "yellow", ocean: "blue" }

zr0gravity7
  • 2,917
  • 1
  • 12
  • 33