Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flattening the nested object in javascript

I ran into this problem, I was able to write solution which can handle array of object (not posted here) or one level deep nested object but i couldn't solve when the given object has nested structure like below. I am curious to know how we can solve this.

const source = {
  a: 1,
  b: {
    c: true,
    d: {
      e: 'foo'
    }
  },
  f: false,
  g: ['red', 'green', 'blue'],
  h: [{
    i: 2,
    j: 3
  }]
};

solution should be

const solution = {
    'a': 1,
    'b.c': true,
    'b.d.e': 'foo',
    'f': false,
    'g.0': 'red',
    'g.1': 'green',
    'g.2': 'blue',
    'h.0.i': 2,
    'h.0.j': 3
};

attempt for one deep nested object

let returnObj = {}

let nestetdObject = (source, parentKey) => {

    let keys = keyFunction(source);

    keys.forEach((key) => {
      let values = source[key];

      if( typeof values === 'object' && values !== null ) {
        parentKey = keys[0]+'.'+keyFunction(values)[0]
        nestetdObject(values, parentKey);
      }else{
        let key = parentKey.length > 0 ? parentKey : keys[0];
        returnObj[key] = values;
      }
    })
    return returnObj
};

// Key Extractor 
let keyFunction = (obj) =>{
  return Object.keys(obj);
}

calling the function

nestetdObject(source, '')

But my attempt will fail if the object is like { foo: { boo : { doo : 1 } } }.

like image 750
Mad-D Avatar asked Feb 27 '19 02:02

Mad-D


People also ask

How do you flatten a nested array of objects?

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. Here, the “Array” object will invoke the “flat()” method while passing “depth” as an argument.

Can you flatten an object JavaScript?

Use the flat() Method to Flatten an Object in JavaScript We will use the flat() method to flatten the value of the individual objects of the main object.

What does it mean to flatten an object JavaScript?

We make a function called flatten object which takes input of an object and returns an object. Loop through the object and check the type of the current property: If it is of type Object and it is not an Array , recursively call the function again. Otherwise, store the value in the result.

How do you flatten data in JavaScript?

Flatten a JSON object: var flatten = (function (isArray, wrapped) { return function (table) { return reduce("", {}, table); }; function reduce(path, accumulator, table) { if (isArray(table)) { var length = table.


2 Answers

You should be able to do it fairly simply with recursion. The way it works, is you just recursively call a parser on object children that prepend the correct key along the way down. For example (not tested very hard though):

const source = {
  a: 1,
  b: {
    c: true,
    d: {
      e: 'foo'
    }
  },
  f: false,
  g: ['red', 'green', 'blue'],
  h: [{
    i: 2,
    j: 3
  }]
}

const flatten = (obj, prefix = '', res = {}) => 
  Object.entries(obj).reduce((r, [key, val]) => {
    const k = `${prefix}${key}`
    if(typeof val === 'object'){ 
      flatten(val, `${k}.`, r)
    } else {
      res[k] = val
    }
    return r
  }, res)
 
console.log(flatten(source))
like image 94
Matt Way Avatar answered Oct 08 '22 06:10

Matt Way


I am very late to the party but it can be easily achieved with a module like Flatify-obj.

Usage:

   const flattenObject = require('flatify-obj');

   flattenObject({foo: {bar: {unicorn: '🦄'}}})
   //=> { 'foo.bar.unicorn': '🦄' }

   flattenObject({foo: {unicorn: '🦄'}, bar: 'unicorn'}, {onlyLeaves: true});
   //=> {unicorn: '🦄', bar: 'unicorn'}
like image 2
rocktimsaikia Avatar answered Oct 08 '22 06:10

rocktimsaikia