我有2个像这样的对象
var row = {
destination: {
id: 1,
name: 'test'
},
name: 'test2',
source: 'source2'
};
var obj = [{'index': 'name'}, {'index': 'source'}, {'index': 'destination.name'}];
现在循环使用obj我可以获取行的值但不能获取destination.name
for(var i=0;i<obj.length;i++){
console.log(row[obj.index]);
}
输出
test2
source2
undefined
答案 0 :(得分:0)
解决您的问题
var row = {
destination: {
id: 1,
name: 'test'
},
name: 'test2',
source: 'source2'
};
var obj = [
{'index': 'name'},
{'index': 'source'},
{'index': {'destination':'name'}}
];
for(var i=0;i<obj.length;i++){
if(typeof(obj[i].index) == 'object'){
var x = obj[i].index;
var key = Object.keys(x)[0];
var innerkey = obj[i].index[key];
console.log(row[key][innerkey]);
} else {
console.log(row[obj[i].index]);
}
}