Search code examples
javascriptreactjslodash

How to flatten objects in JavaScript (with or without lodash)?


I have an object like

farmer:{
  name: "First Name",
  bank: {
    id: 7
  }
  certifications: [
   {
    certificateNumber: {
     id : 7
    },
    certificateNumber: {
     id : 8
    }  
   }
  ]
}

I have tried using lodash's set and unset method but that results in undefined values a lot often.I want to remove the id key from the above object completely

This is the result i want

farmer:{
  name: "First Name",
  bank: 7
  certifications: [
   {
    certificateNumber: 7,
    certificateNumber: 8 
   }
  ]
}

Solution

  • You can use lodash's _.transform() to iterate the structure recursively, and if an object has an id property, and its size (number of properties) is 1, replace the object with the id value.

    Note: the certifications array is malformed and was changed to the following form [{certificateNumber:{id:7}},{certificateNumber:{id:8}}].

    const fn = obj => _.transform(obj, (accumulator, value, key) => {
      let val = value
    
      if(_.has(value, 'id') && _.size(value) === 1) val = _.get(value, 'id')
      else if(_.isObject(value)) val = fn(value)
    
      accumulator[key] = val
    })
    
    const farmer = {"name":"First Name","bank":{"id":7},"certifications":[{"certificateNumber":{"id":7}},{"certificateNumber":{"id":8}}]}
    
    const result = fn(farmer)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.js"></script>