如何在 JavaScript 中将对象数组转换为一个对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19874555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert array of Objects into one Object in JavaScript?
提问by Vijay Chouhan
I have an array of objects:
我有一个对象数组:
[
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }
];
How do I convert it into the following by JavaScript?
如何通过 JavaScript 将其转换为以下内容?
{
"11": "1000",
"22": "2200"
}
采纳答案by Tibos
You're probably looking for something like this:
你可能正在寻找这样的东西:
// 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);
回答by Shevchenko Viktor
Tiny ES6 solution can look like:
微小的 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)
Also, if you use object spread, than it can look like:
此外,如果您使用对象传播,则它看起来像:
var object = arr.reduce((obj, item) => ({...obj, {[item.key]: item.value}}) ,{});
One more solution that is 99% faster is(tested on jsperf):
另一种速度提高 99% 的解决方案是(在 jsperf 上测试):
var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});
Here we benefit from comma operator, it evaluates all expression before comma and returns a last one(after last comma). So we don't copy obj
each time, rather assigning new property to it.
在这里我们受益于逗号运算符,它计算逗号之前的所有表达式并返回最后一个(最后一个逗号之后)。所以我们不会obj
每次都复制,而是为它分配新的属性。
回答by GreQ
I like the functional approach to achieve this task:
我喜欢实现这个任务的函数式方法:
var arr = [{ key:"11", value:"1100" }, { key:"22", value:"2200" }];
var result = arr.reduce(function(obj,item){
obj[item.key] = item.value;
return obj;
}, {});
Note:Last {}
is the initial obj
value for reduce function, if you won't provide the initial value the first arr
element will be used (which is probably undesirable).
注意:last{}
是obj
reduce 函数的初始值,如果您不提供初始值,arr
则将使用第一个元素(这可能是不可取的)。
回答by FirstOne
Trying to fix this answerin How do I convert array of Objects into one Object in JavaScript?,
试图在如何在 JavaScript 中将对象数组转换为一个对象中修复此答案?,
this should do it:
这应该这样做:
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 }) )));
回答by Hedley Smith
A clean way to do this using modern JavaScript is as follows:
使用现代 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" }
回答by Brage
Using 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);
回答by ahhhhhhhhhhhhhhhhhhhhhhhhhhhhh
回答by Adarsh Madrecha
Based on answers suggested by many authors, I created a JsPref test scenario. https://jsperf.com/array2object82364
根据许多作者建议的答案,我创建了一个 JsPref 测试场景。https://jsperf.com/array2object82364
Below are the screenshots of performance. It is a little shocking to me to see, chrome result is in contrast to firefox and edge, even after running it several times.
下面是性能截图。看到 chrome 的结果与 Firefox 和 Edge 形成对比,让我有点震惊,即使在运行了几次之后也是如此。
回答by Paul
Using 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'));
回答by pstadler
Update: The world kept turning. Use a functional approach instead.
更新:世界一直在转动。改用函数式方法。
Here you go:
干得好:
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"}