Javascript: ForEach 遍历子对象
Javascript: ForEach over sub objects
我正在使用 forEach 迭代 javascript 中的一个对象。在我尝试遍历子字段之前,它按预期工作。我将如何使用 forEach 遍历字段和子字段?下面是一段代码以及预期和实际结果。任何帮助将不胜感激:)
const person = {
first: 'Joe',
last: 'Dirt',
previous: {
last: 'Sand',
}
};
const attributes = [
'first',
'last',
'previous.last' <-- Undefined. How do I access this?
];
attributes.forEach(element => {
console.log(person[element]);
});
预期:
-乔
-污垢
-沙子
结果:
-乔
-污垢
-未定义
您可以在临时对象的帮助下迭代拆分属性。
var person = { first: 'Joe', last: 'Dirt', previous: { last: 'Sand', } },
attributes = ['first', 'last', 'previous.last'];
attributes.forEach(function (element) {
var obj = person;
element.split('.').forEach(function (a) {
obj = obj[a];
});
document.write(obj + '<br>');
});
我正在使用 forEach 迭代 javascript 中的一个对象。在我尝试遍历子字段之前,它按预期工作。我将如何使用 forEach 遍历字段和子字段?下面是一段代码以及预期和实际结果。任何帮助将不胜感激:)
const person = {
first: 'Joe',
last: 'Dirt',
previous: {
last: 'Sand',
}
};
const attributes = [
'first',
'last',
'previous.last' <-- Undefined. How do I access this?
];
attributes.forEach(element => {
console.log(person[element]);
});
预期:
-乔
-污垢
-沙子
结果:
-乔
-污垢
-未定义
您可以在临时对象的帮助下迭代拆分属性。
var person = { first: 'Joe', last: 'Dirt', previous: { last: 'Sand', } },
attributes = ['first', 'last', 'previous.last'];
attributes.forEach(function (element) {
var obj = person;
element.split('.').forEach(function (a) {
obj = obj[a];
});
document.write(obj + '<br>');
});