我有一个对象数组:

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

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

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

当前回答

/ /原始 Var arr = [{ 关键:“11”, 价值:“1100”, $ $ hashKey: 00 x ' }, { 关键:“22”, 价值:“2200”, $ $ hashKey:“018” } ]; //我的解决方案 Var obj = {}; 对于(设I = 0;I < arrr .length;我+ +){ obj arr[[我]。Key] = arr[i].value; } console.log (obj)

其他回答

let array = [
  { key: "key1", value: "value1" },
  { key: "key2", value: "value2" },
];

let arr = {};

arr = array.map((event) => ({ ...arr, [event.key]: event.value }));

console.log(arr);

/ /原始 Var arr = [{ 关键:“11”, 价值:“1100”, $ $ hashKey: 00 x ' }, { 关键:“22”, 价值:“2200”, $ $ hashKey:“018” } ]; //我的解决方案 Var obj = {}; 对于(设I = 0;I < arrr .length;我+ +){ obj arr[[我]。Key] = arr[i].value; } console.log (obj)

你可以在一行中将数组的对象合并为一个对象:

const obj = Object.assign({}, ...array);

使用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 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/