繁体   English   中英

如何在 JavaScript 中将对象数组转换为一个对象?

[英]How do I convert array of Objects into one Object in JavaScript?

我有一个对象数组:

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

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

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

微小的 ES6 解决方案可能如下所示:

 var arr = [{key:"11", value:"1100"},{key:"22", value:"2200"}]; var object = arr.reduce( (obj, item) => Object.assign(obj, { [item.key]: item.value }), {}); console.log(object)

此外,如果您使用对象传播,则它看起来像:

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 ,而是为其分配新属性。

试图在如何在 JavaScript 中将对象数组转换为一个对象中修复此答案 ,

这应该这样做:

 var array = [ {key:'k1',value:'v1'}, {key:'k2',value:'v2'}, {key:'k3',value:'v3'} ]; var mapped = array .map(item => ({ [item.key]: item.value }) ); var newObj = Object.assign({}, ...mapped ); console.log(newObj );


单线:

 var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));

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

 // original var arr = [ {key : '11', value : '1100', $$hashKey : '00X' }, {key : '22', value : '2200', $$hashKey : '018' } ]; //convert var result = {}; for (var i = 0; i < arr.length; i++) { result[arr[i].key] = arr[i].value; } console.log(result);

我喜欢实现这个任务的函数式方法:

var arr = [{ key:"11", value:"1100" }, { key:"22", value:"2200" }];
var result = arr.reduce(function(obj,item){
  obj[item.key] = item.value; 
  return obj;
}, {});

注意:最后一个{}是 reduce 函数的初始obj值,如果您不提供初始值,将使用第一个arr元素(这可能是不可取的)。

https://jsfiddle.net/GreQ/2xa078da/

使用Object.fromEntries

 const array = [ { key: "key1", value: "value1" }, { key: "key2", value: "value2" }, ]; const obj = Object.fromEntries(array.map(item => [item.key, item.value])); console.log(obj);

使用现代 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" }

使用lodash

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

根据许多作者建议的答案,我创建了一个 JsPref 测试场景。 https://jsperf.com/array2object82364

下面是性能截图。 看到 chrome 的结果与 Firefox 和 Edge 形成对比,让我有点震惊,即使在运行了几次之后也是如此。

边缘

火狐

铬合金

您可以将一组对象合并为一行中的一个对象:

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'));
let array = [
  { key: "key1", value: "value1" },
  { key: "key2", value: "value2" },
];

let arr = {};

arr = array.map((event) => ({ ...arr, [event.key]: event.value }));

console.log(arr);

使用 reduce 的简单方法

// Input : 
const data = [{key: 'value'}, {otherKey: 'otherValue'}];

data.reduce((prev, curr) => ({...prev, ...curr}) , {});

// Output
{key: 'value', otherKey: 'otherValue'}

使用 Object.assign 更简单

Object.assign({}, ...array);

以下是如何动态接受上述字符串并将其插入到对象中:

var stringObject = '[Object { key="11", value="1100", $$hashKey="00X"}, Object { key="22", value="2200", $$hashKey="018"}]';

function interpolateStringObject(stringObject) {
  var jsObj = {};
  var processedObj = stringObject.split("[Object { ");
  processedObj = processedObj[1].split("},");
  $.each(processedObj, function (i, v) {
      jsObj[v.split("key=")[1].split(",")[0]] = v.split("value=")[1].split(",")[0].replace(/\"/g,'');
  });

  return jsObj
}

var t = interpolateStringObject(stringObject); //t is the object you want

http://jsfiddle.net/3QKmX/1/

 // original var arr = [{ key: '11', value: '1100', $$hashKey: '00X' }, { key: '22', value: '2200', $$hashKey: '018' } ]; // My solution var obj = {}; for (let i = 0; i < arr.length; i++) { obj[arr[i].key] = arr[i].value; } console.log(obj)

您可以为此使用 mapKeys lodash 函数。 只需一行代码!

请参阅此完整代码示例(将其复制粘贴到 repl.it 或类似文件中):

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' } }

临近 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'}

昨天做的

// 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
}, {});
        var obj = [
            {id: 1 , name : 'gaju' , class : 'kv'},
            {id: 2 , name : 'tushar' , class : 'Super'}
        ];

        function conv(obj,arg){
        var temp= {};
        var output= {}
        for(key in obj){
        temp[key] = obj[key];
        };

        var i=0;
        for(key in temp){
        var aa = {};
        var value = temp[key][arg];
        aa[value] = temp[i];
        //console.log(aa[value][arg] );
        output[aa[value][arg]]=  aa[value];
        i++;
        }

       console.log(output); 
        }

calling function 

    conv(obj,'class');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM