0

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' }
Ahmed Younes
  • 964
  • 12
  • 17

2 Answers2

2

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.

Mark
  • 90,562
  • 7
  • 108
  • 148
0

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

Zain Mohsin
  • 97
  • 1
  • 11