how to convert this nested object into a flat object?

Sorry I don't know how to phrase the question title. Please help edit if possible.

I have an object like this:

{
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
           e: 'hahaha'
        }
    }
}

I want to make it look like:

{
    'a': 'jack',
    'b.c': 'sparrow',
    'b.d.e': 'hahaha'
}

// so that I can use it this way:
a['b.d.e']

jQuery is ok too. I know for the nested object, I can use a.b.d.e to get hahaha, but today I have to use it like a['b.d.e'] -_-!!! How can I achieve this? Thanks in advance :)

Answers:

Answer

You could use a recursive function to crawl the object and flatten it for you.

var test = {
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
            e: 'hahaha'
        }
    }
};

function traverseAndFlatten(currentNode, target, flattenedKey) {
    for (var key in currentNode) {
        if (currentNode.hasOwnProperty(key)) {
            var newKey;
            if (flattenedKey === undefined) {
                newKey = key;
            } else {
                newKey = flattenedKey + '.' + key;
            }

            var value = currentNode[key];
            if (typeof value === "object") {
                traverseAndFlatten(value, target, newKey);
            } else {
                target[newKey] = value;
            }
        }
    }
}

function flatten(obj) {
    var flattenedObject = {};
    traverseAndFlatten(obj, flattenedObject);
    return flattenedObject;
}

var flattened = JSON.stringify(flatten(test));
console.log(flattened);

Answer

An alternative recursive implementation. I just felt like writing one implementation myself, even though the current ones are already really good.

The recursive function checks whether the key is of type 'object'.

  • If it's an object, we iterate by each object's key.
  • Else, we add it into our result object.
function flat(res, key, val, pre = '') {
  const prefix = [pre, key].filter(v => v).join('.');
  return typeof val === 'object'
    ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
    : Object.assign(res, { [prefix]: val});
}
return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});

Flat NPM package

Or you can simply use flat npm package, which is a well known tested library.

var flatten = require('flat')
flatten(obj);

? I would use this in serious code.

[Extra] Neater call to the function above

function flatObject(input) {
  function flat(res, key, val, pre = '') {
    const prefix = [pre, key].filter(v => v).join('.');
    return typeof val === 'object'
      ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
      : Object.assign(res, { [prefix]: val});
  }

  return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});
}

const result = flatObject(input);

[Extra] Demo

http://codepen.io/zurfyx/pen/VpErja?editors=1010

function flatObject(input) {
  function flat(res, key, val, pre = '') {
    const prefix = [pre, key].filter(v => v).join('.');
    return typeof val === 'object'
      ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
      : Object.assign(res, { [prefix]: val});
  }

  return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});
}

const result = flatObject({
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
           e: 'hahaha'
        }
    }
});

document.getElementById('code').innerHTML = JSON.stringify(result, null, 2);
<pre><code id="code"></code></pre>

Answer

You could loop through the entries of the object. If the value is an object, recursively call the function. Use flatMap to get a flattened array of entries.

Then use Object.fromEntries() to get an object from the flattened array of entries

const input = {
  a: 'jack',
  b: {
    c: 'sparrow',
    d: {
      e: 'hahaha'
    }
  }
}

const getEntries = (o, prefix = '') => 
  Object.entries(o).flatMap(([k, v]) => 
    Object(v) === v  ? getEntries(v, `${prefix}${k}.`) : [ [`${prefix}${k}`, v] ]
  )

console.log(
  Object.fromEntries(getEntries(input))
)

Note: Object(v) === v returns true only for objects. typeof v === 'object' is true for v = null too.

Answer

Recursive is the best solution for this case.

function flatten(input, reference, output) {
  output = output || {};
  for (var key in input) {
    var value = input[key];
    key = reference ? reference + '.' + key : key;
    if (typeof value === 'object' && value !== null) {
      flatten(value, key, output);
    } else {
      output[key] = value;
    }
  }
  return output;
}
var result = flatten({
  a: 'jack',
  b: {
    c: 'sparrow',
    d: {
      e: 'hahaha'
    }
  }
});
document.body.textContent = JSON.stringify(result);

Answer

An aproach with a recursive function, an iteration over the object's keys and a look up if the value is an object. if so, make a call with the updated function. Otherwise add the found value to the result object.

function getValues(o, a) {
    Object.keys(o).forEach(function (k) {
        if (typeof o[k] === 'object') {
            getValues(o[k], [].concat(a, k));
            return;
        }
        result[[].concat(a, k).join('.')] = o[k];
    });
}

var object = { a: 'jack', b: { c: 'sparrow', d: { e: 'hahaha' } } },
    result = {};

getValues(object);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Answer

Just an example how can you achieve that with ES6 features.

const flatObject = obj => {
    const keys = Object.keys(obj)

    return keys.reduce((acc, k) => {
        const value = obj[k]

        return typeof value === 'object' ?
             {...acc, ...ObjectUtils.flatObject(value)} :
             {...acc, [k]: value}
    } , {})
}
Answer

Another approach using ES6.

const obj = {
  a: "jack",
  b: {
    c: "sparrow",
    d: {
      e: "hahaha"
    }
  }
};

function flattenObj(value, currentKey) {
  let result = {};

  Object.keys(value).forEach(key => {

    const tempKey = currentKey ? `${currentKey}.${key}` : key;

    if (typeof value[key] !== "object") {
      result[tempKey] = value[key];
    } else {
      result = { ...result, ...flattenObj(value[key], tempKey) };
    }
  });

  return result;
}

console.log(flattenObj(obj));
Answer

2020

The simplest algorithm ever. Even easy to remember :)

// option 1: just leafs
export function flatObject(obj) {
    const flatObject = {};
    const path = [];

    function dig(obj) {
        if (obj !== Object(obj))
            /*is primitive ?*/
            return flatObject[path.join('.')] = obj;
        for (let key in obj) {
            path.push(key);
            dig(obj[key]);
            path.pop();
        }
    }

    dig(obj);
    return flatObject;
}

example

let  obj = {aaa:{bbb:{c:1,d:7}}, bb:{vv:2}}
console.log(flatObject(obj))
/*
{
  "aaa.bbb.c": 1,
  "aaa.bbb.d": 7,
  "bb.vv": 2
}
*/
// option 2: return all paths. shorter and simpler. 
export function flatObject(obj) {
    const flatObject = {};
    const path = [];

    function dig(obj) {
        for (let key in obj) {
            path.push(key);
            flatObject[path.join('.')] = dig(obj[key]);
            path.pop();
        }
        return obj;
    }

    dig(obj);
    return flatObject;
}

example:

let  obj = {aaa:{bbb:{c:1,d:7}}, bb:{vv:2}}
console.log(flatObject(obj))
/*{
  "aaa.bbb.c": 1,
  "aaa.bbb.d": 7,
  "aaa.bbb": {
    "c": 1,
    "d": 7
  },
  "aaa": {
    "bbb": {
      "c": 1,
      "d": 7
    }
  },
  "bb.vv": 2,
  "bb": {
    "vv": 2
  }
}
*/
Answer

Try this

const result = [].concat.apply([], parentArray.map((item: any) => item.any)

Answer

var flattenObject = function(ob) {
  var toReturn = {};

  for (var i in ob) {
    if (!ob.hasOwnProperty(i)) continue;

    if ((typeof ob[i]) == 'object' && ob[i] !== null) {
      var flatObject = flattenObject(ob[i]);
      for (var x in flatObject) {
        if (!flatObject.hasOwnProperty(x)) continue;

        toReturn[i + '.' + x] = flatObject[x];
      }
    } else {
      toReturn[i] = ob[i];
    }
  }
  console.log(toReturn)
  return toReturn;
};

var ob = {
  'a': {
    'b': {
      'b2': 2
    },
    'c': {
      'c2': 2,
      'c3': 3
    }
  }
};
flattenObject(ob);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.