5

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

1 Answer 1

10

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Works like a charm. I am using this on Firebase to make a copy from a node.

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.