简体   繁体   English

如何在一个特定对象中转换对象数组?

[英]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. PS如果您向我提供有关如何完成此任务的知识链接,我将感到高兴。

Thank you. 谢谢。

An alternative using the function reduce 使用函数reduce的替代方案

Brief explanation 简要说明

  • The function Array.prototype.reduce loops an array applying a handler for each object. 函数Array.prototype.reduce循环一个数组,为每个对象应用一个处理程序。
  • The accumulator a will contain the result from each iteration. 累加器a将包含每次迭代的结果。
  • The function converter receives the accumulator and the current object. 功能converter接收累加器和当前对象。
  • This Object.assign(a, {[name]: value}) assigns a new property to the current accumulator. Object.assign(a, {[name]: value})将新属性分配给当前累加器。
  • Computed property names {[name]: value} that code will build an object as follow: 计算属性名称 {[name]: value}该代码将构建一个对象,如下所示:
{ 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. 数组.reduce方法非常适合。 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 . 无论何时您想要处理数组并提出单个值,您都希望使用array.reduce You can choose the direction (reduce or reduceRight) and the accumulator function, to produce the value (or object) desired. 您可以选择方向(reduce或reduceRight)和累加器函数,以生成所需的值(或对象)。

Another way using reduce, destructurization and object spread operator: 使用reduce,destructurization和object spread操作符的另一种方法:

 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. 您也可以使用forEach()来解决它。

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() : 您可以使用Array.map(){ [name]: value }的形式创建对象数组,并通过传播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: 你可以用for循环来解决这个问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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