1

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

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? Commented Feb 24, 2019 at 3:05

2 Answers 2

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; }

Sign up to request clarification or add additional context in comments.

3 Comments

Lovely. Makes sense now. Thanks!
Man, the more I learn about this language, the more neat things I can do with it. Creative answer!
@RonGilchrist yw!
2

Just for completeness 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.