考虑一个对象
var obj = {
val: 123,
vals: {
val: 45,
vals: {
val: 90
}
},
name: 'abc',
names: {
name: 'xyz'
}
};
我需要这样的东西:
var obj = {
val: 123,
vals_val: 45,
vals_vals_val: 90,
name: 'abc',
names_name: 'xyz'
};
有人能告诉我如何进入嵌套对象并访问属性及其值?我尝试了.in循环但没有任何想法。
答案 0 :(得分:6)
您可以使用reduce()
方法并返回新对象作为结果。
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)

答案 1 :(得分:0)
你可以这样做。我要举一个例子:
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);
您可以使用“.
”
答案 2 :(得分:0)
您可以采用递归方式并删除与新密钥不同的项目。
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);