Home > Net >  How to split children in object to separate arrays
How to split children in object to separate arrays

Time:11-02

This might be an odd question, but I'm working on a project and can't seem to figure this one out. I need to be able to take a Javascript Object like this:

{
    field1: {
        field2: {
            field3: "value 1",
            field4: "value 2"
        }
    }
}

And take any field that has more than one key, and split the results into separate arrays like this:

[
    {
        field1: {
            field2: {
                field3: "value 1"
            }
        }
    },
    {
        field1: {
            field2: {
                field4: "value 2"
            }
        }
    }
]

I've tried building a few recursive functions that will traverse the object structure, and anytime a value is of type object and has more than one key, I try to copy the object and give each "child" it's own parent structure. I don't know if this makes much sense but I've been stuck on this for a while and feel like I'm maybe just overlooking something simple that can get this job done.

I appreciate any input. Thank you!

CodePudding user response:

Here's a quick sample on your original input.

But more test cases with valid output would be needed to verify. (It definitely goes off the rails quickly)

const input = {
  field1: {
    field2: {
      field3: "value 1",
      field4: "value 2"
    }
  }
}

function recursivelyFlatten(obj) {
  const result = [];

  for (const [k, v] of Object.entries(obj)) {
    if (v && typeof v === 'object' && [...Object.entries(v)].length) {
      for (const o of recursivelyFlatten(v)) {
        result.push({ [k]: o })
      }
    }
    else {
      result.push({ [k]: v })
    }
  }

  return result;
}

console.log(JSON.stringify(recursivelyFlatten(input), null, 2))

Further samples:

function recursivelyFlatten(obj) { const result = []; for (const [k, v] of Object.entries(obj)) { if (v && typeof v === 'object' && [...Object.entries(v)].length) { for (const o of recursivelyFlatten(v)) { result.push({ [k]: o }); } } else { result.push({ [k]: v }); } } return result; }

// Input 1
const input1 = {
  field1: {
    field2: {
      field3: "value 1",
      field4: "value 2"
    }
  },
  field5: {
    field6: {
      field7: "value 3"
    },
    field8: {
      field9: "value 4"
    }
  }
}

console.log(recursivelyFlatten(input1));

// Input 2
const input2 = {
  field1: {
    field2: {
      field3: {
        f3_1: 'v3_1',
        f3_2: 'v3_2',
      },
      field4: "value 2"
    }
  }
}

console.log(recursivelyFlatten(input2));

  • Related