Consider an object
var obj = {
val: 123,
vals: {
val: 45,
vals: {
val: 90
}
},
name: 'abc',
names: {
name: 'xyz'
}
};
I need something like this :
var obj = {
val: 123,
vals_val: 45,
vals_vals_val: 90,
name: 'abc',
names_name: 'xyz'
};
Can someone tell me how do I get into a nested object and access the properties and its value? I tried for..in loop but not getting any idea.
You can use reduce() method and return new object as result.
var obj = {"val":123,"vals":{"val":45,"vals":{"val":90}},"name":"abc","names":{"name":"xyz"}}
function keys(data, prev = '') {
return Object.keys(data).reduce(function(r, e) {
var key = prev + (prev.length ? '_' + e : e)
if (typeof data[e] == 'object') Object.assign(r, keys(data[e], key))
else r[key] = data[e]
return r;
}, {})
}
var r = keys(obj)
console.log(r)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With