Max Wolfen
Max Wolfen

Reputation: 2023

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 not know it clearly.

The task:

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

On output we must have:

let obj = {width:300, height: 100};

The count of array objects can be infinity.

P.S. I'll be pleased if you provide me with link on knowleges to how make this task done.

Thank you.

Upvotes: 3

Views: 278

Answers (9)

Nerdi.org
Nerdi.org

Reputation: 923

var len = arr.length, 

var newA = []; 
let width, height, item; 
for(var x = 0; x < len; x+=2){ //add 2 for pair loop because width/height in diff array objects 
 item.width = arr[x].value;
 item.height = arr[x+1].value; 
 newA.push(item); 
 // newA = [{width:value, height:value}, {width:value, height:value}];
}
console.log(newA);

This should work for grouping width and height together in your final array :)

If you want just one big object (make sure there are no name duplicates !)...

var len = arr.length, 
obj = {}; 
for(var x = 0; x < len; x++){ 
 obj[arr[x].name] = arr[x].value;
} 
console.log(obj);

Upvotes: 0

Ele
Ele

Reputation: 33726

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; }
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>

Upvotes: 5

Ori Drori
Ori Drori

Reputation: 191976

You can use Array.map() to create an array of objects in the form of { [name]: value }, and merge them to a single object by spreading into Object.assign():

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

const object = Object.assign(...arr.map(({ name, value }) => ({ [name]: value })));

console.log(object);

Upvotes: 0

Mahipal
Mahipal

Reputation: 519

You can use forEach() to solve it as well.

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

Upvotes: 0

Karen Grigoryan
Karen Grigoryan

Reputation: 5422

Another way using reduce, destructurization and object spread operator:

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

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


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

console.log(out);

Upvotes: 1

CRice
CRice

Reputation: 32146

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);

Upvotes: 3

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

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.

Upvotes: 1

Dan Raps
Dan Raps

Reputation: 318

You can solve this with just a for loop:

var obj = {};
for (var i=0; i<arr.length; i++){
    obj[arr[i].name] = arr[i].value;
}

Upvotes: -1

Pac0
Pac0

Reputation: 23149

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);

Upvotes: 0

Related Questions