0

I have this data structure and want to change it using lodash using keyBy

[
  {
    names: [
      {
        id: 1,
        name: 'aa',
      },
      {
        id: 2,
        name: 'bb',
      },
    ],
    date: '2020-11-02',
  },
  {
    names: [
      {
        id: 3,
        name: 'cc',
      },
    ],
    date: '2020-11-10',
  },
]

And would like to use lodash to to change it so it's just an object of objects where every single name is an object with the id as a reference. Don't really care if the date is removed or not don't need it. It should look something like this.

  1: {
    id: 1,
    name: 'aa',
  },
  2: {
    id: 2,
    name: 'bb',
  },
  3:{
    id: 3,
    name: 'cc',
  }

Tried doing this but it just returns an empty object

_.chain(array)
      .keyBy('id')
      .mapValues(function (item) {
        item.name= _.keyBy(item.name, 'id')
        return item
      })
      .value()
2
  • 1
    It would be really helpful if you added the desired output to your question. Commented Nov 11, 2020 at 21:03
  • My apologies. I have updated the question. Commented Nov 11, 2020 at 21:10

2 Answers 2

2

This isn't using lodash, but this is as simple as:

.flatMap(i => i.names)
.reduce((c, i) => {
    c[i.id] = i;
    return c;
}, {})

console.log([
  {
    names: [
      {
        id: 1,
        name: 'aa',
      },
      {
        id: 2,
        name: 'bb',
      },
    ],
    date: '2020-11-02',
  },
  {
    names: [
      {
        id: 3,
        name: 'cc',
      },
    ],
    date: '2020-11-10',
  },
].flatMap(i => i.names)
    .reduce((c, i) => {
        c[i.id] = i;
        return c;
    }, {}))

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

3 Comments

I was going to provide an answer with a double reduce but flatMap rocks. I should remember it more frequently.
Oh really nice solution. Yeah flatMap is really nice :)
If you want to show your solution using double reduce I would still like to take a look at it :) Always nice to know more then one solution and reduce confuses the hell out of me!
1

With lodash you can use _.flatMap() to convert the names to a single array, and then use _.keyBy() to convert to an object:

const arr = [{"names":[{"id":1,"name":"aa"},{"id":2,"name":"bb"}],"date":"2020-11-02"},{"names":[{"id":3,"name":"cc"}],"date":"2020-11-10"}]

const result = _.keyBy(
  _.flatMap(arr, 'names'),
  'id'
)

console.log(result)
<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.