3

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.

3
  • You can use reduce function probably Commented Nov 28, 2019 at 7:34
  • any explanation on how to achieve this ? I really newbie in this javascript thing. Commented Nov 28, 2019 at 7:39
  • You could just loop over the keys and add them to a new object that is sorted like your example. Commented Nov 28, 2019 at 7:39

6 Answers 6

8

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 })

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

Comments

3

loop through the entries on the answer object like this -

let a =
{
    "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"
    }
};

//map of sections by section name
let m = new Map();
for (let [key, value] of Object.entries(a.answer))
{
  let sectionName = key.charAt(0);
  let section = m.get(sectionName);
  if (!section)
  {
    section =
    {
      sectionName
    };
    m.set(sectionName, section);
  }
  section[key] = value;
}
//create final object
let b =
{
  answer: [...m.entries()].sort(([k1], [k2]) => k1.localeCompare(k2))
               .map(([key, value]) => value)
};
console.log(b);

//map of sections by section name
let m = new Map();
for (let [key, value] of Object.entries(a.answer))
{
  let sectionName = key.charAt(0);
  let section = m.get(sectionName);
  if (!section) {
    section = {
      sectionName
    };
    m.set(sectionName, section);
  }
  section[key] = value;
}
//create final object
let b = {
  answer: [...m.entries()].sort(([k1], [k2]) => k1.localeCompare(k2))
               .map(([key, value]) => value)
};

Comments

1

You could group with the sectionName and an object as hash table and get only the value of it as result.

var data = { 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" } },
    result = Object.values(Object.entries(data.answer).reduce((r, [k, v]) => {
        var sectionName = k[0];
        r[sectionName] = r[sectionName] || { sectionName };
        r[sectionName][k] = v;
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

Hope this helps

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 key_map = {}
const final = {
  answer: []
}
Object.keys(input.answer).map(key => {
  if (!key_map[key[0]]) {
    key_map[key[0]] = {
      "sectionName": key[0]
    }
  }
  key_map[key[0]][key] =input.answer[key]
})

Object.values(key_map).map((v) => {
  final.answer.push(v)
})

console.log(final)

Comments

0

Should work

let myObject = {
  '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'
  }
}
let myResult = []
for (let index in myObject.answer) {
  let sectionName = index.substr(0, 1)
  let indexFound = myResult.findIndex(r => r.sectionName === sectionName)
  if (indexFound >= 0) {
    myResult[indexFound][index] = myObject.answer[index]
  } else {
    myResult.push({ 'sectionName': sectionName })
    myResult[(myResult.length - 1)][index] = myObject.answer[index]
  }
}
console.log({
  answer: myResult
})

Comments

0

const jsonInout = `{
  "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"
  }
}`;

// Parse response
let obj = JSON.parse(jsonInout, null, 2).answer;

// Get sections
const sections = Array.from(new Set(Object.keys(obj).map(key => {
  return key[0];
})));

// Get splitted object
const splitted = {
  answer: sections.map(sectionKey => {
    let section = { sectionName: sectionKey };
    for (let [key, value] of Object.entries(obj)) {
      if (key[0] === sectionKey) section[key] = value;
    }
    return section;
  })
};

console.log(splitted);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.