0
const _ = require('lodash');
const parentDetails = [
    {
        'name': '5003',
        'id': '1'
    },
    {
        'name': '5000',
        'id': '2'
    }
];
const childrenDetails = [
    {
        'cid': '11',
        'Reference': '5003'
    },
    {
        'cid': '22',
        'Reference': '5000'
    }
]; 

Desired Output using lodash library: Extract matching reference from the second array with the name of the first array and append the matching child detail as an object to the first array as shown below. The result should not mutate the original array.

result = [
    {
        'name': '5003',
        'id': '1',
        'childrenDetail' : {
            'cid': '11',
            'Reference': '5003'
        }
    },
    {
        'name': '5000',
        'id': '2',
        'childrenDetail' : {
            'cid': '22',
            'Reference': '5000'
        }
    }
];
3
  • I don't think you need lodash for this, what have you tried so far? Commented Aug 12, 2021 at 16:09
  • result = []; for (const i of parentDetails ) { for (const j of childrenDetails ) { if (i.name === j.reference) { i.childrenDetail = j; result.push(i); } } } Commented Aug 12, 2021 at 16:13
  • I want the same output using lodash library. This is part of a task. Commented Aug 12, 2021 at 16:15

1 Answer 1

1

Here is an example using _.find()

const result = parentDetails.map(elm => {
   const childrenDetail = _.find(childrenDetails, elm2 => elm2.Reference === elm.name);
   if (childrenDetail) return ({...elm, childrenDetail});
});
console.log(result);

You can also replace array.map() with _.map().

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

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.