Search code examples
javascriptarraysobjectnested-object

simplifying a nested javascript object


I have an object that looks like this:

var someUglyObject = 
{
    "1-1" : {foo1: "foo1-1Value", bar1: "bar1-1value"},
    "1-2" : {foo2: "foo1-2Value", bar2: "bar1-2value"},
    "2-1" : {foo2: "foo2-1Value", bar2: "bar2-1value"},
    "2-2" : {foo2: "foo2-2Value", bar2: "bar2-2value"}
}

I need to simplify the nested object above and convert into a simpler object after some processing (concatenation) like below:

var myObj = { 
             "1": { propsTogether : "foo1-1Valuebar1-1valuefoo1-2Valuebar1-2value"},
             "2": { propsTogether : "foo2-1Valuebar2-1valuefoo2-2Valuebar2-2value" }
        }

My plan is to interate through the keys like this, but not sure how to group the props together based on the first char of the key , i.e. for a key with value of '2-1' - 2 should be the new key.

var myObj= {};
Object.keys(someUglyObject).forEach(function(key) {

}

Solution

  • You can use Object.keys and reudce

    Here idea is

    • First get the keys out of object.
    • Sort them // Object don't have order
    • Now split key on - and use first element as key on op object.
    • Use object.values and join them in desired format and place it on respective key

    var obj = {'1-1' : {foo1: "foo1-1Value", bar1: "bar1-1value"},'1-2' : {foo2: "foo1-2Value", bar2: "bar1-2value"},'2-1' : {foo2: "foo2-1Value", bar2: "bar2-1value"},'2-2' : {foo2: "foo2-2Value", bar2: "bar2-2value"}}
    
    
    let op = Object.keys(obj).sort().reduce((op,inp)=>{
      let key = inp.split('-',1)[0]
      op[key] = op[key] || {props:''}
      op[key].props = op[key].props + Object.values(obj[inp]).join('')
      return op
    },{})
    
    console.log(op)