Mohammed Rabiulla RABI
Mohammed Rabiulla RABI

Reputation: 493

hyphen separated string from complex object

let person={
    id: 01,
    name:'john',
    age:'21',
    address:{
        city:{
            city_name:'Mumbai',
            pin:54321
        },
        state: 'Maharashtra',
        country:'india',
        street:'Main street'
    }
}
function flat(myobj){
    for (item in myobj)
    {
        if(typeof item === 'Object')
        {
            flat(item);
        }
        console.log(item+'-'+myobj[item]+'\n');
    }
}




flat(person);

The above code which i tried

I am trying to convert this object into a flat hyphen separated string . but i got stuck while accessing nested object, I am getting out but is,

id-1

name-john

age-21

address-[object Object]

my expected output

id-1

name-john

age-21

address-city-city_name-mumbai-pin-54321-state-maharashtra-country-india....

any suggestion where i am wrong and any other optimization needed.

Upvotes: 0

Views: 101

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138257

item is the objects key, thus typeof item is always "string". You might want to check typeof myobj[item] === "object" instead ... Additionally you need a way to keep track of nested keys when doing the recursive call, that can be done by passing the previous keys with the call:

function flat(obj, prev = ""){
  for (let key in obj) {
     if(typeof obj[key] === "object") {
        flat(obj[key], prev + "-" + key);
     } else {
       console.log((prev ? prev + "-" : "") + key + ": " + obj[key]);
     }
   }
 }

Here's how I'd write that:

 function keyValuePairs(obj, prev = []) {
   for(const [key, value] of Object.entries(obj)) {
      if(typeof value === "object") {
         yield* keyValuePairs(value, [...prev, key]);
      } else yield [[...prev, key].join("-"), value];
   }
 }

 const result = Object.fromEntries(keyValuePairs({ /*...*/ }));

Upvotes: 3

Related Questions