javascript - Create a single object from an array of objects - JSES6 - Stack Overflow

I have an array:[{"allocateProd1": "30.0000"}, {"allocateProd2": "

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
Add a ment  | 

2 Answers 2

Reset to default 6

An 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信