0

say I have an array :

[ { name: 'A', count: 100 }, { name: 'B', count: 200 } ]

how can I get an object :

{ A : 100, B : 200 }

2 Answers 2

2

Try utilizing Array.prototype.forEach() to iterate properties , values of array , set properties of new object to properties , values of input array

var arr = [ { name: 'A', count: 100 }, { name: 'B', count: 200 } ];
// create object 
var res = {};
// iterate `arr` , set property of `res` to `name` property of 
// object within `arr` , set value of `res[val.name]` to value
// of property `count` within `arr`
arr.forEach(function(val, key) {
  res[val.name] = val.count
});
console.log(res);
Sign up to request clarification or add additional context in comments.

Comments

1

Looks like a great opportunity to practice using Array.prototype.reduce (or reduceRight, depending on desired behaviour)

[{name: 'A', count: 100}, {name: 'B', count: 200}].reduceRight(
    function (o, e) {o[e.name] = e.count; return o;},
    {}
); // {B: 200, A: 100}

This could also be easily modified to become a summer,

o[e.name] = (o[e.name] || 0) + e.count;

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.