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.
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.
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.
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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With