0

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

}
1
  • 2
    Isn't the second object much uglier than the first (they're both not pretty, but the second is completely unreadable) Commented Apr 3, 2019 at 17:09

1 Answer 1

1

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)

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

4 Comments

Looks beautiful! Thank you for the explanation!!
@AJSwift always happy to help :)
how do I simply extract the nested objects like {1 : { {foo1: "foo1-1Value", bar1: "bar1-1value"}, {foo2: "foo1-2Value", bar2: "bar1-2value"}}, 2: { {..}, {..} } ?
@AJSwift that's not a valid format you need to have key:value pair in JSON, 1 : { {foo1: "foo1-1Value", this is not.

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.