Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript split JSON object by key

I have a situation where i need to split the Json Object given by back-end using the key. Here is the example of the JSON the back-end gave.

{
    "answer": {
        "E2": "Tony Stark",
        "E3": "1",
        "E4": "2",
        "E6": "4",
        "E8": "9120",
        "E9": "01",
        "F1": "Marvel",
        "F2": "1",
        "F4": "2",
        "F6": "4",
        "F8": "9120",
        "F9": "01",
        "G1": "02",
        "G2": "02",
        "G3": "02",
        "H10": "Car"
    }
}

Is it possible for me to split the answer into per section E, F, G and H ? Expected result to be

{
    "answer": [
        {
            "E2": "Tony Stark",
            "E3": "1",
            "E4": "2",
            "E6": "4",
            "E8": "9120",
            "E9": "01",
            "sectionName": "E"
        },
        {
            "F1": "Marvel",
            "F2": "1",
            "F4": "2",
            "F6": "4",
            "F8": "9120",
            "F9": "01",
            "sectionName": "F"
        },
        {
            "G1": "02",
            "G2": "02",
            "G3": "02",
            "sectionName": "G"
        },
        {
            "H10": "Car",
            "sectionName": "H"
        }
    ]
}

There must be a genius out there that might be able to solve my question. Thank you so much. Any advise is appreciated.

like image 374
ameruddin jamil Avatar asked May 16 '26 16:05

ameruddin jamil


1 Answers

Loop through the entries of the object and group them based on the first letter of the key. If the group object alrady has the the letter as key, update it. Else, add the letter as key to the group object. Use Object.values() to get the array of answer needed in the output

const input={answer:{E2:"Tony Stark",E3:"1",E4:"2",E6:"4",E8:"9120",E9:"01",F1:"Marvel",F2:"1",F4:"2",F6:"4",F8:"9120",F9:"01",G1:"02",G2:"02",G3:"02",H10:"Car"}};

const group = {};

for (const [k, v] of Object.entries(input.answer)) {
  const sectionName = k.charAt(0);
  if (group[sectionName])
    group[sectionName][k] = v;
  else
    group[sectionName] = { sectionName, [k]: v };
}

const answer = Object.values(group)

console.log({ answer })
like image 53
adiga Avatar answered May 18 '26 06:05

adiga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!