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. JS/ES6 solution will help
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. JS/ES6 solution will help
Share Improve this question edited Feb 24, 2019 at 2:27 Ele 33.8k7 gold badges43 silver badges80 bronze badges asked Feb 24, 2019 at 2:26 Rajdeep ChowdhuriRajdeep Chowdhuri 652 silver badges8 bronze badges 1- "This array is dynamically generated as in the number of objects inside varies depending on data" Is the expected result for property names to be overwritten? – guest271314 Commented Feb 24, 2019 at 3:05
2 Answers
Reset to default 6An alternative is using the function 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
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 pleteness by taking the array and spread ...
the objects into Object.assign
with an object as target. Voilà!
var array = [{ allocateProd1: "30.0000"}, { allocateProd2: "0"}, { allocateProd3: "0"}, { allocateProd4: "30"}],
object = Object.assign({}, ...array);
console.log(object);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745656700a4638583.html
评论列表(0条)