0

I have an array and an object with different properties from the elements of the array, but they are linked together by their common identifier. The array has the following structure:

[{
userId: '12',
prop1: 'blue',
prop2: 'yellow'
},
{
userId: '13',
prop1: 'black',
prop2: 'white'
}]

My object has the following structure:

{id: '13',
prop3: 'heavy',
prop4: 'light'}

I would like to append the object to the array by their given Id, so at the end the array would look like this:

[{
userId: '12',
prop1: 'blue',
prop2: 'yellow'
},
{
userId: '13',
prop1: 'black',
prop2: 'white',
prop3: 'heavy',
prop4: 'light'
}]

As the identifier for the id is not the same, I'm having a hard time to merge them. I have tried merging via lodash using the following code, but haven't had any luck. Thank you!

let merged = _(myArray)
          .concat(myObject)
          .groupBy('id')
          .map(_.spread(_.merge))
          .value();

2 Answers 2

1

Change the object 'id' prop to `userId' before merging:

const mergeToArr = (arr, { id: userId, ...rest }) => _(arr)
  .concat({ userId, ...rest })
  .groupBy('userId')
  .map(_.spread(_.merge))
  .value();
          
const arr = [{"userId":"12","prop1":"blue","prop2":"yellow"},{"userId":"13","prop1":"black","prop2":"white"}];1
const obj = {"id":"13","prop3":"heavy","prop4":"light"};

const result = mergeToArr(arr, obj);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

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

Comments

1

Pardon me for asking but why do you want to do this in that particular fashion? It seems to me rather expensive. It can also be done with a single map and merge:

const arr = [{"userId":"12","prop1":"blue","prop2":"yellow"},{"userId":"13","prop1":"black","prop2":"white"}];1
const obj = {"id":"13","prop3":"heavy","prop4":"light"};

let mergeObjToArr = (o, a) => 
   _.map(a, x => _.isEqual(o.id, x.userId) ? _.merge(_.omit(o, ['id']), x) : x)

console.log(mergeObjToArr(obj, arr))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

If you consider this you have map/merge/omit vs chain/concat/groupBy/map/spread/merge/value.

This also can easily be converted to ES6 and skip lodash completely.

Unless I am miss-understanding this for which I apologize if it is the case.

1 Comment

thank you for your response, there was no particular reason for doing it that way, your solution is indeed more efficient. In the end, I decided to convert your solution to ES6, which gave me the fastest execution! :)

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.