Search code examples
javascriptarraysecmascript-6ecmascript-5

Split up single object into multiple objects


I have a single JSON object that I would like to split up into multiple objects. I've tried converting the single JSON object into an array. I couldn't figure out a pattern to break up the single object if there's an absent key, i.e. meal1, meal2, etc. I'm not even sure if this is the best approach. I appreciate any help or pointers in the right direction!

Before

{
  "fullName1" : "John Doe",
  "attendance1" : 1,
  "meal1" : "salmon",
  "fullName2" : "Jane Doe",
  "attendance2" : 0
}

Desired result

{
  "fullName" : "John Doe",
  "attendance" : 1,
  "meal" : "salmon"
},
{
  "fullName" : "Jane Doe"
  "attendance" : 0
}

As far as my attempt, this is how far I've gotten:

const entries = [...elements];
// check for valid elements
const isValidElement = element => {
  return element.name && element.value;
};
const isValidValue = element => {
  return (!['radio'].includes(element.type) || element.checked);
};
const formToJSON = elements =>
  [].reduce.call(elements, (data, element) => {
    if (isValidElement(element) && isValidValue(element)) {
      data[element.name] = element.value;
    }
    return data;
  }, {});
//
const singleArray = formToJSON(entries);

Solution

  • You can use Object.entries and reduce like below to achieve this

    Loop through every record in the object, and store last digits from the key in temp Object.

    let obj = {
      "fullName1" : "John Doe",
      "attendance1" : 1,
      "meal1" : "salmon",
      "fullName2" : "Jane Doe",
      "attendance2" : 0
    }
    
    let res = Object.entries(obj).reduce((o, [k, v]) => {
        let [name, number] = k.match(/\D+|\d+$/g)
        o[number] = { ...(o[number] || {}), [name]: v }
        return o
      }, {})
      
    console.log(Object.values(res))