Raj*_*uri 0 javascript arrays object ecmascript-6 reactjs
我有一个数组:
[
{"allocateProd1": "30.0000"},
{"allocateProd2": "0"},
{"allocateProd3": "0"},
{"allocateProd4": "30"}
]
Run Code Online (Sandbox Code Playgroud)
该数组是动态生成的,因为内部对象的数量取决于数据
我需要一个对象:
{
"allocateProd1": "30.0000",
"allocateProd2": "0",
"allocateProd3": "0",
"allocateProd4": "30"
}
Run Code Online (Sandbox Code Playgroud)
通常会在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);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)
替代方法是使用功能 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);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
475 次 |
最近记录: |