我有一个对象数组:

[ 
  { 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);

你可以使用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' } }

是昨天做的

// 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);

坐地lodash !

const obj = _.keyBy(arrayOfObjects, 'keyName')