我有一个对象数组:

[ 
  { key : '11', value : '1100', $$hashKey : '00X' },
  { key : '22', value : '2200', $$hashKey : '018' }
];

如何通过JavaScript将其转换为以下内容?

{
  "11": "1100",
  "22": "2200"
}

当前回答

使用reduce的简单方法

// Input : 
const data = [{key: 'value'}, {otherKey: 'otherValue'}];

data.reduce((prev, curr) => ({...prev, ...curr}) , {});

// Output
{key: 'value', otherKey: 'otherValue'}

使用Object.assign更简单

Object.assign({}, ...array);

其他回答

这应该做到:

Var数组= [ {key: 'k1', value: 'v1'}, {key: 'k2', value: 'v2'}, {键:'k3',值:'v3'} ]; Var mapped = array。Map (item => ({[item。关键:项目。Value})); var newObj =对象。分配({},……映射); console.log (newObj);


One-liner:
var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));

更新:世界一直在转。使用函数式方法。


以前的回答

给你:

var arr = [{ key: "11", value: "1100" }, { key: "22", value: "2200" }];
var result = {};
for (var i=0, len=arr.length; i < len; i++) {
    result[arr[i].key] = arr[i].value;
}
console.log(result); // {11: "1000", 22: "2200"}

在2022年附近,我喜欢这种方法,特别是当对象数组是动态的时,这也是基于@AdarshMadrecha的测试用例场景的建议,

const array = [ 
  { key : '11', value : '1100', $$hashKey : '00X' },
  { key : '22', value : '2200', $$hashKey : '018' }];
  
let obj = {};
array.forEach( v => { obj[v.key] = v.value }) //assign to new object
console.log(obj) //{11: '1100', 22: '2200'}

我喜欢用函数方法来完成这个任务:

var arr = [{ key:"11", value:"1100" }, { key:"22", value:"2200" }];
var result = arr.reduce(function(obj,item){
  obj[item.key] = item.value; 
  return obj;
}, {});

注意:Last{}是reduce函数的初始obj值,如果你不提供初始值,第一个arr元素将被使用(这可能是不可取的)。

https://jsfiddle.net/GreQ/2xa078da/

坐地lodash !

const obj = _.keyBy(arrayOfObjects, 'keyName')