我有一个对象数组:
[
{ 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"
}
当前回答
使用现代JavaScript的一种干净的方法如下:
const array = [
{ name: "something", value: "something" },
{ name: "somethingElse", value: "something else" },
];
const newObject = Object.assign({}, ...array.map(item => ({ [item.name]: item.value })));
// >> { something: "something", somethingElse: "something else" }
其他回答
你可以使用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' } }
使用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',值:'1100',$$hashKey: '00X'}, {key: '22',值:'2200',$$hashKey: '018'} ]; / /转换 Var结果= {}; For (var I = 0;I < arrr .length;我+ +){ 结果(arr[我]。Key] = arr[i].value; } console.log(结果);
你可以在一行中将数组的对象合并为一个对象:
const obj = Object.assign({}, ...array);
更新:世界一直在转。使用函数式方法。
以前的回答
给你:
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"}