How to deeply remove keys in object?

Viewed 382

I have this json object returned from an API that has a few quirks, and I'd like to normalize it so I can process the input the same for every response. These means getting rid of superfluous keys:

Response:

{
  _links: {...},
  _embedded: {
    foo: [
      {
        id: 2,
        _embedded: {
          bar: []
        }
      }
    ]
  }
}

So I'd like to remove all the _embedded keys and flatten it, like so:

{
  _links: {...},
  foo: [
    {
      id: 2,
      bar: []
    }
  ]
}

This is what I have at the moment, but it only works for the top level and I don't think it'll play well with arrays.

_.reduce(temp1, function(accumulator, value, key) {
  if (key === '_embedded') {
    return _.merge(accumulator, value);
  }
  return accumulator[key] = value;
}, {})
3 Answers
Related