Skip to content Skip to sidebar Skip to footer

How To Convert Array Of Objects In One Specific Object?

So, I had the very tiny, but hard for me task from my last interview. I just itreseted in how to solve it. I think that we need to implement the recursion in this task, but I do no

Solution 1:

An alternative using the function reduce

Brief explanation

  • The function Array.prototype.reduce loops an array applying a handler for each object.
  • The accumulator a will contain the result from each iteration.
  • The function converter receives the accumulator and the current object.
  • This Object.assign(a, {[name]: value}) assigns a new property to the current accumulator.
  • Computed property names{[name]: value} that code will build an object as follow:
{ width: 300 }

let arr = [{name: 'width', value: 300},{name: 'height', value: 100}],
    converter = (a, {name, value}) => (Object.assign(a, {[name]: value})),
    obj = arr.reduce(converter, {});

console.log(obj);
.as-console-wrapper { max-height: 100%!important; top: 0; }
<scriptsrc="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>

Solution 2:

The array .reduce method would be a good fit. Start with an empty object and for each array item, add an entry to the object with that key and value. Example:

let arr = [{name: 'width', value: 300}, {name: 'height', value: 100}];

let result = arr.reduce((combo, item) => {
    combo[item.name] = item.value;
    return combo;
}, {});

console.log(result);

Solution 3:

First, you're missing a comma between your two objects in the array :)

Whenever you're looking to process an array and come up with a single value, you're looking to use array.reduce. You can choose the direction (reduce or reduceRight) and the accumulator function, to produce the value (or object) desired.

Solution 4:

Another way using reduce, destructurization and object spread operator:

const src = [{
  name: 'width',
  value: 300
}, {
  name: 'height',
  value: 100
}]

constreducer = (acc, { name, value }) => ({
  ...acc,
  ...{ [name]: value }
});


const out = src.reduce(reducer, {});

console.log(out);

Solution 5:

You can create the object by adding the key value pairs in the array, with the help of the bracket notations :

let arr = [{name: 'width', value: 300},{name: 'height', value: 100}];
 let obj = {};
 arr.forEach(pair => obj[pair.name] = pair.value)
 console.log(obj);

Post a Comment for "How To Convert Array Of Objects In One Specific Object?"