我有一个对象数组:

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

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

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

当前回答

使用Underscore.js:

var myArray = [
  Object { key="11", value="1100", $$hashKey="00X"},
  Object { key="22", value="2200", $$hashKey="018"}
];
var myObj = _.object(_.pluck(myArray, 'key'), _.pluck(myArray, 'value'));

其他回答

使用Underscore.js:

var myArray = [
  Object { key="11", value="1100", $$hashKey="00X"},
  Object { key="22", value="2200", $$hashKey="018"}
];
var myObj = _.object(_.pluck(myArray, 'key'), _.pluck(myArray, 'value'));

使用reduce的简单方法

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

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

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

使用Object.assign更简单

Object.assign({}, ...array);
let array = [
  { key: "key1", value: "value1" },
  { key: "key2", value: "value2" },
];

let arr = {};

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

console.log(arr);

使用Object.fromEntries:

Const数组= [ {key: "key1", value: "value1"}, {key: "key2", value: "value2"}, ]; const obj = Object.fromEntries(array.map(item => [item. map])键,item.value])); console.log (obj);

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

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/