javascriptobjectkey-valuenest-nested-object

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' }

Solution

  • 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.