Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of objects with specific key, then remove that key from object

Tags:

lodash

I have used lodash to create an array of objects from a specific key, then remove this given key from its object.

I have this

var cars = [{
        "itemID": "-KUsw42xU-S1qA-y3TiI", // use this as key
        "name": "Car One",
        "qtd": "1"
    },
    {
        "itemID": "-KUsw42xU-r1qA-s3TbI",
        "name": "Car Two",
        "qtd": "2"
    }
]

Trying to get this:

var cars = {
    "-KUsw42xU-S1qA-y3TiI": {
        "name": "Car One",
        "qtd": "1"
    },
    "-KUsw42xU-r1qA-s3TbI": {
        "name": "Car Two",
        "qtd": "1"
    }
}

I have tried this approach, but I have no success.

 _.chain(a)
  .keyBy('itemID')
  .omit(['itemID'])
  .value();
like image 304
calebeaires Avatar asked Jan 06 '23 03:01

calebeaires


1 Answers

You were nearly there. To omit the itemID from each object you need to map the values (using mapValues):

var result = _.chain(cars)
  .keyBy('itemID')
  .mapValues( v => _.omit(v, 'itemID'))
  .value();
like image 69
Gruff Bunny Avatar answered Feb 21 '23 23:02

Gruff Bunny