我有一个对象数组:
[
{ 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"
}
当前回答
使用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);
其他回答
是昨天做的
// Convert the task data or array to the object for use in the above form
const {clientData} = taskData.reduce((obj, item) => {
// Use the clientData (You can set your own key name) as the key and the
// entire item as the value
obj['clientData'] = item
return obj
}, {});
使用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(结果);
微小的ES6解决方案可以看起来像:
var arr =[{关键:“11”,值:" 1100 "},{关键:“22”,值:" 2200 "}); Var对象= arr.reduce( (obj, item) =>对象。赋值(obj,{[项目。关键:项目。Value}), {}); console.log(对象)
同样,如果你使用对象扩展,它可以看起来像:
var object = arr.reduce((obj, item) => ({...obj, [item.key]: item.value}) ,{});
还有一个更快99%的解决方案是(在jsperf上测试):
var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});
这里我们受益于逗号运算符,它计算逗号之前的所有表达式,并返回最后一个(在最后一个逗号之后)。因此,我们不是每次都复制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);