[英]Create a single object from an array of objects - JS/ES6
我有一個數組:
[
{"allocateProd1": "30.0000"},
{"allocateProd2": "0"},
{"allocateProd3": "0"},
{"allocateProd4": "30"}
]
該數組是動態生成的,因為其中的對象數取決於數據
我需要一個對象:
{
"allocateProd1": "30.0000",
"allocateProd2": "0",
"allocateProd3": "0",
"allocateProd4": "30"
}
通常會在React中使用它。 JS / ES6解決方案將有所幫助
一種替代方法是使用函數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; }
另一種方法是使用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; }
為了完整Object.assign
,通過將數組作為對象並將對象散布到...
Object.assign
。 瞧!
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.