0

I have a small problem.

I have such an array of objects:

Array
[
  0: {
    name: "someName",
    value: "someValue"
  },
  1: {
    name: "someName",
    value: "someValue"
  }
  ...
]

I would like to get:

Object
{
  "someName": "someValue",
  "someName": "someValue",
  ...
}

It is very easy to map... but I do not know how to properly assign this to an object

myArray.map(element => console.log(element.name, element.value));
Adee
  • 357
  • 1
  • 3
  • 13
  • 1
    Use ```array#reduce``` – Wainage Sep 27 '17 at 15:30
  • Not exactly. This is the situation where the array has arrays. – Adee Sep 27 '17 at 15:39
  • Your `.map()` was just logging, and not actually mapping to a new array. If each `.map()` iteration returned a new object with a new key-value pair, you could then use the resulting array with `Object.assign`. – llama Sep 27 '17 at 15:41
  • Like this: `var result = Object.assign({}, ...data.map(element => ({[element.name]: element.value})));` – llama Sep 27 '17 at 15:41
  • Or this: `var result = Object.assign({}, ...data.map(({name, value}) => ({[name]: value})))` – llama Sep 27 '17 at 15:43
  • 1
    Or use `.reduce()` like this: `var result = data.reduce((res, {name, value}) => Object.assign(res, {[name]: value}), {})` – llama Sep 27 '17 at 15:46
  • llama, Thank you!!! – Adee Sep 27 '17 at 15:46

0 Answers0