0

I am trying to achieve it Like a:1,b:2:,c:3,e:4,g:5,h:6 But not getting success.

Facing error this. But is the best way to do it.

const input = {
  a: 1,
  b: 2,
  c: 3,
  d: {
    e: 4,
    f: {
      g: 5,
      h: 6
    }
  }
}


const getValue = (values) => {
  for (let i in Object.keys(values)) {
    if (Object.keys(values[Object.keys(values)[i]]).length > 0) {
      console.log('v', Object.keys(values)[i])
      getValue(Object.keys(values)[i])
    } else {
      //        console.log(Object.keys(values)[i],Object.values(values)[i])
    }
  }
}
getValue(input)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Rover
  • 661
  • 2
  • 18
  • 39

3 Answers3

1

You can iterate through each key of object and for object value recursively call your getValue() function.

const input = { a:1, b:2, c:3, d:{ e:4, f:{ g:5, h:6 } } } 

const getValue = (values) => { 
  for (const key of Object.keys(values)) { 
    if(typeof values[key] === 'object' && values[key] !== null) {
      getValue(values[key]);
    } else {
      console.log(`${key}: ${values[key]}`);
    }
  }
}

getValue(input);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

Edited : you can do something like this

 const input = {a:1,b:2,c:3,d:{e:4,f:{g:5,h:6 }}}
    
    
    Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(input))


//{a: 1, b: 2, c: 3, e: 4, g: 5, …} 

you can see more details here

Ayoub Bousetta
  • 176
  • 2
  • 6
0

You could use recursion to get the desired result.

const input = {
  a: 1,
  b: 2,
  c: 3,
  d: {
    e: 4,
    f: {
      g: 5,
      h: 6,
    },
  },
};

const result = {};
function getValues(obj) {
  for (let key in obj) {
    if (typeof obj[key] !== `object`) result[key] = obj[key];
    else getValues(obj[key]);
  }
}

getValues(input);
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42