how to inject by keys pair value using lodash in node js

My jsob object look like this

{"LAB_123":{"abc":"bde"},"LAB_345":{"abc":"efg"}}

Second json object is

{"LAB_123":{"xyz":"dfe"},"LAB_345":{"PQR":"ABC"}}

I need to join those two object to create one json array which should look like this

{"LAB_123":{"abc":"bde","xyz":"dfe"},"LAB_345":{"abc":"efg","PQR":"ABC"}}

I can add keys values using looping through the json array but is there any method using lodash which will make this code look easier.

1 answer

  • answered 2017-06-17 18:29 Ori Drori

    You can use lodash's _.merge(), which recursively merges the object. Since merge mutates the 1st object (the 1st param), use an empty object to avoid mutating the original objects:

    const a = {"LAB_123":{"abc":"bde"},"LAB_345":{"abc":"efg"}};
    
    const b = {"LAB_123":{"xyz":"dfe"},"LAB_345":{"PQR":"ABC"}};
    
    const result = _.merge({}, a, b);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    If you want an array of objects, you can split the result of the 1st example using _.toPairs() to key/value pairs, and map them to objects:

    const a = {"LAB_123":{"abc":"bde"},"LAB_345":{"abc":"efg"}};
    
    const b = {"LAB_123":{"xyz":"dfe"},"LAB_345":{"PQR":"ABC"}};
    
    const result = _({})
      .merge(a, b)
      .toPairs()
      .map(([key, value]) => ({ [key]: value }))
      .value();
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>