2

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?

2

2 Answers 2

8

You can use Array.prototype.reduce as follows.

const list = Object.entries(result).reduce((acc, [k, v]) => {
  acc[k] = v.lists;
  return acc;
}, {});
Sign up to request clarification or add additional context in comments.

Comments

3

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>

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.