-1

I have an object like this:

const myObj = {
  a: {
    b: {
      c: 1,
      d: 2
    },
    f: {
      z: 4,
      u: 6
    }
  }
}

into this:

const myObj = [
  {
    c: 1,
    d: 2,
  },
  {
    z: 4,
    u: 6,
  }
]

I found this: How to recursively transform an array of nested objects into array of flat objects? but the original is an array of objects, and mine is an object itself.

2
  • What is the exact criteria for flattening? Commented May 5, 2021 at 18:32
  • what if a value and an object is in an object? Commented May 5, 2021 at 18:38

1 Answer 1

0

You can traverse the values of the objects until you reach the leaves (objects with no values that are other objects).

const myObj = {
  a: {
    b: {
      c: 1,
      d: 2
    },
    f: {
      z: 4,
      u: 6
    }
  }
};
const flatObj = o => Object.values(o).some(x => x === Object(x)) ?
  Object.values(o).flatMap(flatObj) : [o];
console.log(flatObj(myObj))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.