我有一个对象数组:

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

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

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

当前回答

在2022年附近,我喜欢这种方法,特别是当对象数组是动态的时,这也是基于@AdarshMadrecha的测试用例场景的建议,

const array = [ 
  { key : '11', value : '1100', $$hashKey : '00X' },
  { key : '22', value : '2200', $$hashKey : '018' }];
  
let obj = {};
array.forEach( v => { obj[v.key] = v.value }) //assign to new object
console.log(obj) //{11: '1100', 22: '2200'}

其他回答

你可能正在寻找这样的东西:

/ /原始 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"}

使用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'));

是昨天做的

// 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
}, {});