Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flatten nested object using lodash

flatten, flattenDeep or flattenDepth of lodash only accept array. How to flatten nested object?

var data = {
  "dates": {
    "expiry_date": "30 sep 2018",
    "available": "30 sep 2017",
    "min_contract_period": [{
      "id": 1,
      "name": "1 month",
      "value": false
    }, {
      "id": 2,
      "name": "2 months",
      "value": true
    }, {
      "id": 3,
      "name": "3 months",
      "value": false
    }]
  },
  "price": {
    "curreny": "RM",
    "min": 1500,
    "max": 2000
  }
}

I want nested property to be the first level, like expiry_date should be level 1, not within dates, and I think dates should be gone, it's not needed anymore. I can do it manually, use map() but I'm looking to use lodash to ease the task.

like image 767
Giala Jefferson Avatar asked Mar 07 '17 10:03

Giala Jefferson


People also ask

How do you flatten a nested array of objects?

The “Array. flat()” method is embedded in ES6 that enables you to “flatten” a nested JavaScript Array. This method returns a new array in which all of the elements of sub-arrays are concatenated according to the specified depth.

How to flatten array lodash?

The Lodash. flatten() method is used to flatten the array to one level deep. Parameter: This method accepts single parameter array that holds simple array or array of arrays. Return Value: The return type of this function is array.

How do you flatten an object in an array?

You use the flat() method for concatenating sub-arrays recursively into a single array. The flat() method takes a depth value as its parameter which is optional depending on the depth of the array you wish to flatten (concatenate). The flat() method takes in 1 as a depth by default.


1 Answers

One of the easiest solutions would be, merging the nested object with parent,

_.merge(data, data.dates);

This will bring all data.dates property into data. Then delete data.dates

delete data.dates
like image 155
RaR Avatar answered Oct 01 '22 10:10

RaR