简体   繁体   中英

what is the best way to map Javascript object with Quoted keys

I have received data from API like this

var myObj = {'name':'ahmed','age':37,'tools':{'dev1':"macbook",'dev2':"iphone",'dev3':"tablet"},'gender':'male'};

What is the best way to make it key-value pairs note that there are nested objects?

update Thanks for the answer this is if I don't want to flatten my object

var myObj = {'name':'ahmed','age':37,'tools':{'dev1':"macbook",'dev2':"iphone",'dev3':"tablet"},'gender':'male'};


function unQuoteKeys(obj, newObj ={}){
    Object.keys(obj).forEach(key => {
          newObj[key] = obj[key]
    });
    return newObj
}
console.log(unQuoteKeys(myObj));

result

{ name: 'ahmed',
  age: 37,
  tools: { dev1: 'macbook', dev2: 'iphone', dev3: 'tablet' },
  gender: 'male' }

It sounds like you want to flatten this whole object into a single set of key-value pairs. You can do this with a simple recursive function that adds the key/values to the return object if they are simple values, or recurses if the values are objects:

 var myObj = {'name':'ahmed','age':37,'tools':{'dev1':"macbook",'dev2':"iphone",'dev3':"tablet"},'gender':'male'}; function flatten(obj, res ={}){ Object.keys(obj).forEach(key => { if (typeof obj[key] === 'object') flatten(obj[key], res) else res[key] = obj[key] }) return res } console.log(flatten(myObj)) 

If there's the possibility that you will have duplicate keys anywhere in the object, this will need a bit more work.

If you want to flatten your object, you can also use lodash _flatten() method. Works like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM