Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Nested object

Tags:

javascript

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.

like image 871
roxid Avatar asked Feb 27 '26 08:02

roxid


1 Answers

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)
like image 63
Nenad Vracar Avatar answered Mar 02 '26 14:03

Nenad Vracar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!