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.

roxid
  • 493
  • 4
  • 14
  • The object you are talking about is also known as a "dictionary". Have a look at the selected answer to this question: https://stackoverflow.com/questions/11734417/javascript-equivalent-of-pythons-values-dictionary-method – Adriano Nov 21 '17 at 20:21
  • look at this https://stackoverflow.com/questions/33036487/one-liner-to-flatten-nested-object – Abid Nawaz Nov 21 '17 at 20:25

3 Answers3

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • 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 – roxid Nov 21 '17 at 20:36
  • 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` – mhodges Nov 21 '17 at 20:45
  • If any of the values are `Date` objects, this solution omits the property altogether. – mhodges Nov 21 '17 at 20:52
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 '.'

Oqhax
  • 419
  • 1
  • 4
  • 16
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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392