calebeaires
calebeaires

Reputation: 2084

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

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();

Upvotes: 5

Views: 1577

Answers (1)

Gruff Bunny
Gruff Bunny

Reputation: 27976

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();

Upvotes: 10

Related Questions