简体   繁体   English

我如何从对象数组中获取对象

[英]How can i get an object from an array of objects

At the entrance I have such an array with objects. 在入口处,我有一个带有对象的数组。 Function that converts an incoming array of objects into an object. 将传入的对象数组转换为对象的函数。 Using the function, I need to bring it to this form. 使用该函数,我需要将其转换为这种形式。

var array = [ 
   { k1:v1 },
   { k2:v2 },
   { k3:v3 }
];

function arrayToObject(array) { return object }

var object = { 
    v1: k1,
    v2: k2,
    v3: k3, 
}

You could taske Object.assign and spread the reversed objects. 您可以对Object.assign任务分配并散布反转的对象。

 var array = [ { k1: 'v1' }, { k2: 'v2' }, { k3: 'v3' }], object = Object.assign(...array.map(o => Object .entries(o) .reduce((r, [k, v]) => Object.assign(r, { [v] : k }), {}) )); console.log(object); 

Use forEach loop 使用forEach循环

 var array = [ { k1:'v1' }, { k2:'v2' }, { k3:'v3' } ] function a() { var obj={}; array.forEach((e)=>obj[e[Object.keys(e)[0]]]=Object.keys(e)[0]) console.log(obj) } a(); 

You can use Object.entries() and .reduce() methods to get the desired output: 您可以使用Object.entries().reduce()方法获取所需的输出:

 const array = [ { k1:'v1' }, { k2:'v2' }, { k3:'v3' } ]; const obj = Object.entries( array.reduce((r, c) => Object.assign(r, c), {}) ).reduce((r, [k, v]) => (r[v] = k, r), {}); console.log(obj); 

Array.reduce and use Object.keys over each array element. Array.reduce并在每个数组元素上使用Object.keys

 var array = [ { k1: 'v1' }, { k2: 'v2' }, { k3: 'v3' } ] var obj = array.reduce((obj, item) => { Object.keys(item).forEach(key => obj[item[key]] = key) return obj }, {}) console.log(obj) 

And another one: 还有一个:

 const result = {};

 for(const [[key, value]] of array.map(Object.entries))
   result[value] = key;

I am not sure why the other answers go through hoops to make this as clever as possible. 我不确定为什么其他答案会尽可能地巧妙。

I find this more readable. 我觉得这更具可读性。 I am not using reduce because I find the word misleading. 我没有使用reduce,因为我发现这个词具有误导性。 A simple forEach makes more sense to me 简单的forEach对我来说更有意义

 const array = [ { k1:'v1' }, { k2:'v2' }, { k3:'v3' } ]; let newObj={}; array.forEach((obj) => { let key = Object.keys(obj)[0]; newObj[obj[key]]=key; }) console.log(newObj) 

your answer.. 你的答案..

 var array = [ { k1: v1 }, { k2: v2 }, { k3: v3 } ]; function arrayToObject(array) { obj = {}; for (i = 0; i < array.length; i++) { o = array[i]; key = Object.keys(o)[0]; obj.key = o.key; } return obj; } console.log(arrayToObject(array)) 

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

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