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));
7
  • 1
    Use array#reduce Commented Sep 27, 2017 at 15:30
  • Not exactly. This is the situation where the array has arrays. Commented Sep 27, 2017 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. Commented Sep 27, 2017 at 15:41
  • Like this: var result = Object.assign({}, ...data.map(element => ({[element.name]: element.value}))); Commented Sep 27, 2017 at 15:41
  • 1
    Or use .reduce() like this: var result = data.reduce((res, {name, value}) => Object.assign(res, {[name]: value}), {}) Commented Sep 27, 2017 at 15:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.