[英]Create a single object from an array of objects - JS/ES6
I have an array: 我有一个数组:
[
{"allocateProd1": "30.0000"},
{"allocateProd2": "0"},
{"allocateProd3": "0"},
{"allocateProd4": "30"}
]
This array is dynamically generated as in the number of objects inside varies depending on data 该数组是动态生成的,因为其中的对象数取决于数据
I need an object: 我需要一个对象:
{
"allocateProd1": "30.0000",
"allocateProd2": "0",
"allocateProd3": "0",
"allocateProd4": "30"
}
Mostly going to use it in React. 通常会在React中使用它。 JS/ES6 solution will help JS / ES6解决方案将有所帮助
An alternative is using the function reduce
+ spread syntax
. 一种替代方法是使用函数reduce
+ spread syntax
。
let arr = [ {"allocateProd1": "30.0000"}, {"allocateProd2": "0"}, {"allocateProd3": "0"}, {"allocateProd4": "30"} ]; let result = arr.reduce((a, c) => ({...a, ...c}), Object.create(null)); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The alternative is using the function Object.assign
另一种方法是使用Object.assign
函数
let arr = [ {"allocateProd1": "30.0000"}, {"allocateProd2": "0"}, {"allocateProd3": "0"}, {"allocateProd4": "30"} ]; let result = arr.reduce((a, c) => Object.assign(a, c), Object.create(null)); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Just for completeness by taking the array and spread ...
the objects into Object.assign
with an object as target. 为了完整Object.assign
,通过将数组作为对象并将对象散布到...
Object.assign
。 Voilà! 瞧!
var array = [{ allocateProd1: "30.0000"}, { allocateProd2: "0"}, { allocateProd3: "0"}, { allocateProd4: "30"}], object = Object.assign({}, ...array); console.log(object);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.