0

I have the object coming in from server as shown below :-

[
    { 
        "gender": {
            "male": 25,
            "female": 22
        },
        "population": {
            "pop_under": -23 ,
            "pop_over": 10,
        }
    }
]

I want to extract the key as nameand value as value for above object which after modification looks like this :-

[
   {
       gender : [
           {
               name : "male",
               value : 25
           }, 
           {
               name : "female",
               value : 22
           }
       ], 
       population : [
           {
               name: "pop_under" , 
               value : "-23"
           }, 
           {
               name: "pop_over" , 
               value : "10"
           }
       ]
   } 
]

How can perform said modification? And is it useful to use lodashpackage for this ? Thank you very much for your help.

2
  • Please visit help center, take tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output, preferably in a Stacksnippet Commented Jul 5, 2020 at 13:24
  • 6
    There are seriously HUNDREDS of dupes of this at SO Commented Jul 5, 2020 at 13:24

2 Answers 2

1

You can user reducer for creating new object and Object.keys for looping object fields:

const newData = data.reduce((acc,rec) => {
  return [...acc, Object.keys(rec).reduce((iacc,irec)=>{
    return {...iacc, 
             [irec]: (Object.keys(rec[irec]).map((item)=>{
               return {name: item, value: rec[irec][item]}
             }))
           } 
  },{})]
}, [])

See full example in the playground: https://jscomplete.com/playground/s528735

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

Comments

1

Using .map and Object.keys method.

let result =[];
data.forEach(obj => {
    Object.keys(obj).forEach(key=>{ 
      let response = Object.
                         keys(obj[key]).
                         map(property=> (
                                          {
                                            name: `${property}`, 
                                            value:obj[key][property]
                                          }
                                        )
                            );
     result.push({[key]:response});
    });
});
console.log(result);

Comments

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.