0

I'm having a array of object which I want to convert into object with key as the array of object's key's value and value as array of object's value's value.

Suppose I have an array like this

let arr = [
{name: "abcd", value: "xyz"},
{name: "pqr", value: "uvw"},
....
]

I want to create an object from this array like this.

obj = {
abcd: "xyz",
pqr: "uvw",
...
}

I want to take the value of the key and value and use them to create a new object. Is there any way to do this.?

Pratheek R
  • 63
  • 3
  • 2
    _"Is there any way...?"_ - Yes. What have you tried so far to solve this on your own? -> [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Apr 07 '21 at 13:03
  • Do you know for sure that `arr` will not containt two or more items with the same `name`? And, you can have two items with the same `name`, what would the output object expected to be? – secan Apr 07 '21 at 13:09

3 Answers3

2

Try this:

let arr = [
  {name: "abcd", value: "xyz"},
  {name: "pqr", value: "uvw"}
]
const result = {}
arr.forEach((element) => {
  result[element.name] = element.value
})
console.log(result)
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
1

There are two main different ways I see you could achieve this fairly easily:

1. The .reduce() method

let arr = [
  {name: "abcd", value: "xyz"},
  {name: "pqr", value: "uvw"},
  // ...
];

obj = arr.reduce((a,c) => (a[c.name] = c.value, a), {});

console.log(obj);

2. The Object.values() and Object.fromEntries() method

let arr = [
  {name: "abcd", value: "xyz"},
  {name: "pqr", value: "uvw"},
  // ...
];

obj = Object.fromEntries(arr.map(e => Object.values(e)));

console.log(obj);
Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36
0

You can easily achieve this with reduce. The reduce uses an aggregator function and expects an initial value. You can supply the initial value as an empty object and provide the aggregator function as mentioned below:

const arr = [
  {name: "abcd", value: "xyz"},
  {name: "pqr", value: "uvw"}
];

const result = arr.reduce((a, x) => {
    return {
      ...a,
      [x.name]:x.value
    }
}, {});

console.log(result);
Krantisinh
  • 1,579
  • 13
  • 16