0

I have a JSON Object with an infinite level of objects inside. I want to frame a JSON Array where it contains the first key in a key and all the associated value in another key.

For eg, The JSON I am having is below,

{
    doingnow: {
        "action items": { "open": { "child"....}, "In Progress": { "child"....}, "Completed": { "child"....} },
        "financial": { "q1": { "jan 2017": { "child"... }, "feb 2017": {....} }, q2: {... }, q3: {... },....}
    },
    finished: { "discarded": {... } },
    .........
}

But the actual JSON Array which I am expecting

[{
    key: "doingnow": children: [{
        key: "action items", children: [{ key: "open", children: [] }, { key: "In Progress", children: [] }, { key: "Completed", children: [] }],
        key: "financial", children: [{ key: q1, children: [{ key: "jan 2017", children: [] }, { key: "feb 2017", children: [] }] },
        { key: q2, children: [{ key: "jan 2017", children: [] }, { key: "feb 2017", children: [] }] }]
    }],
}, { key: "finished", children: [{ ...}] }

Can anyone help me with this? Working on it for 2 days. :-(

2
  • 2
    Could you show us what you've tried and what doesn't work? Commented Jul 20, 2020 at 9:43
  • 1
    By "infinite", you mean "arbitrary"? Commented Jul 20, 2020 at 9:46

1 Answer 1

1

This a situation where recursion is probably the best choice.

const data = '{doingnow: ... your string ... }'
const jsonObject = JSON.parse(data)

const parseObject = (obj) => {
  let returnArray = []

  Object.keys(obj).forEach(key => {
    let childrens = []

    if (typeof obj[key] === 'object' && obj[key] !== null) {
      childrens = parseObject(obj[key])
    }

    returnArray.push({key: key, children: childrens})
  })
  
  return returnArray
}

const result = parseObject(jsonObject)

NB. this should work fine for most object, but you may need some more optimization for huge json objects

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

1 Comment

Hi Thank you so much. I got the solution. Much appreciated one. You saved my time. :-)

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.