3

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.

2

3 Answers 3

6

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Can you please tell me logic or overview of the code you have given? I am not expecting line by line explanation, just a little overview or approach.Thanks
arrays pass typeof == "object", and their elements will turn into keys. This will bomb if any of the values are an array. A better (yet still not bulletproof) check would be typeof data[e] === "object" && Object.getPrototypeOf(data[e]) === Object.prototype
If any of the values are Date objects, this solution omits the property altogether.
0

You can do it like this. I'm going to set an example:

var John = {
  age: 23,
  address: {
    Paris: "La rue",
    London: "Tower street"
  },
  surname: "Smith"
};

document.write("Address 1: " + John.address.Paris);
document.write("Surname: " + John.surname);
document.write("Age: " + John.age);

You can access each value with the '.'

Comments

0

You could take a recursice approach and delete the items which has not the same key as the new key.

function update(object) {
    function iter(o, p) {
        Object.keys(o).forEach(function (k) {
            var t;
            if (o[k] && typeof o[k] === 'object') {
                iter(o[k], p.concat(k));
            } else {
                t = p.concat(k).join('_');
                object[t] = o[k];
            }
            if (k !== t) {
                delete o[k];
            }
        });
    }
    iter(object, []);
}

var object = { val: 123, vals: { val: 45, vals: { val: 90 } }, name: 'abc', names: { name: 'xyz' } };

update(object);

console.log(object);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.