How can I convert an object with nested objects to a simple object?

  • 0
    I have an object obj = {a: 100, b: 152, c: {y: 133, x: {m: 20}}} I need to convert it to an object without nesting, that is, obj = {a: 100, b : 152, y: 133, m: 20} tell me how you can do this?
    JavaScript Connor Porter, May 30, 2019

  • 3 Answers
  • 0
    const flatObj = obj =>
    Object.entries(obj).reduce((acc, [ k, v ]) => (
    v instanceof Object && !Array.isArray(v)
    ? Object.assign(acc, flatObj(v))
    : acc[k] = v,
    acc
    ), {});
    Anonymous

  • 0
    const obj = { a: 100, b: 152, c: { y: 133, x: { m: 20} } }
    const flatObject = (current) => {
    return Object.keys(current).reduce((acc, cur) => {
    if (typeof(current[cur]) !== 'object') {
    acc[cur] = current[cur]
    } else {
    acc = {...acc, ...flatObject(current[cur]) }
    }
    return acc
    }, {})
    }

    console.log(flatObject(obj))
    Anonymous

  • 0
    []. concat.apply ([], obj);
    Fynn Johnson

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!