我有一个对象数组:
[
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }
];
如何通过JavaScript将其转换为以下内容?
{
"11": "1100",
"22": "2200"
}
我有一个对象数组:
[
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }
];
如何通过JavaScript将其转换为以下内容?
{
"11": "1100",
"22": "2200"
}
当前回答
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数组= [ {key: 'k1', value: 'v1'}, {key: 'k2', value: 'v2'}, {键:'k3',值:'v3'} ]; Var mapped = array。Map (item => ({[item。关键:项目。Value})); var newObj =对象。分配({},……映射); console.log (newObj);
var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));
坐地lodash !
const obj = _.keyBy(arrayOfObjects, 'keyName')
你可以使用mapKeys lodash函数。只有一行代码!
请参考这个完整的代码示例(复制粘贴到repl。它或类似):
import _ from 'lodash';
// or commonjs:
// const _ = require('lodash');
let a = [{ id: 23, title: 'meat' }, { id: 45, title: 'fish' }, { id: 71, title: 'fruit' }]
let b = _.mapKeys(a, 'id');
console.log(b);
// b:
// { '23': { id: 23, title: 'meat' },
// '45': { id: 45, title: 'fish' },
// '71': { id: 71, title: 'fruit' } }
使用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'));
你可以在一行中将数组的对象合并为一个对象:
const obj = Object.assign({}, ...array);