简体   繁体   中英

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.

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

Thank you.

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> 

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

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.

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

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM