joynerj9j
joynerj9j

Reputation: 11

javascript/lodash: cleaner way to spread properties?

I have a piece of data below. It's an object that contains 2 nested objects with arrays nested in those:

let data = {
    obj1: {
       names: ['joe'],
       ages: false,
    },
    obj2: {
       names: ['james'],
       ages: true,
    },
}

I want to return:

 {
   names: ['james','joe'],
   ages: true,
 }

Right now, I am doing this with:

  const foo = Object.entries(data)[0][1] ?? [];
  const foo2 = Object.entries(data)?.[1]?.[1] ?? [];

  const finalData = {...foo, ...foo2 }

how can I clean that up using loDash's groupBy?

Upvotes: 0

Views: 342

Answers (1)

Ori Drori
Ori Drori

Reputation: 193087

Use _.values() to get the two sub-objects, and then merge them using _.mergeWith(). If the values are an array, concat them, if not let _.mergeWith() handle the merge by returning undefined:

const data = {
    obj1: {
       names: ['joe', 'james'],
       ages: false,
    },
    obj2: {
       names: ['james'],
       ages: true,
    },
}

const result = _.mergeWith(
  {}, ..._.values(data),
  (a, b) => _.isArray(a) ? _.uniq([...a, ...b]) : undefined
)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>

Upvotes: 1

Related Questions