Reputation: 189
I have an object like below.
{
A: { lists: 2, list: [ [Object], [Object] ] },
B: { lists: 2, list: [ [Object], [Object] ] },
C: { lists: 1, list: [ [Object]] }
}
After I do a map on an object list result, like below
const list = Object.entries(result).map(([k, v]) => ({[k]: v.lists}));
the result I am getting is
[{"A":2},{"B":2},{"C":1}]
But what I actually want is
{A: 2, B: 2, C: 1}
How can I achieve that?
Upvotes: 2
Views: 102
Reputation: 191976
When you map the entries change them to [k, v.lists]
, and then convert to an object using Object.fromEntries()
:
const result = { A: { lists: 2 }, B: { lists: 2 }, C: { lists: 1 }};
const list = Object.fromEntries(Object.entries(result).map(([k, v]) => [k, v.lists]));
console.log(list);
With lodash you can use _.mapValues()
to use lists
as the values of the properties:
const result = { A: { lists: 2 }, B: { lists: 2 }, C: { lists: 1 }};
const list = _.mapValues(result, 'lists');
console.log(list);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
Upvotes: 3
Reputation: 10193
You can use Array.prototype.reduce
as follows.
const list = Object.entries(result).reduce((acc, [k, v]) => {
acc[k] = v.lists;
return acc;
}, {});
Upvotes: 8