Search code examples
javascriptlodash

How to create a specific new object from an existing one using lodash


I currently have this array of objects:

[{
   "key1": "value1",
   "key2": "value2",
   "key3": "valuex"
},{
   "key1": "value3",
   "key2": "value4",
   "key3": "valuey"
}]

What I would like to get in the end is an array of strings

["value1/value2", "value3/value4"]

preferrably using some "lodash magic shortcut".

So essentially, I would like to join the values of key1 and key2 to a string using '/' as a separator while ignoring key3.

I tried a lot using _.transform and _.join but none of my attempts were even close to the desired result. I know that this is not a free coding service, but maybe you have a hint for me?


Solution

  • Use lodash.map.

    var data = [{
      "key1": "value1",
      "key2": "value2",
      "key3": "valuex"
    }, {
      "key1": "value3",
      "key2": "value4",
      "key3": "valuey"
    }]
    
    console.log(_.map(data, ob => `${ob.key2}/${ob.key2}`));
    <script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>