javascript - How to get the inner object value dynamically -
this question has answer here:
i have 2 objects this
var row = { destination: { id: 1, name: 'test' }, name: 'test2', source: 'source2' }; var obj = [{'index': 'name'}, {'index': 'source'}, {'index': 'destination.name'}];
now looping on obj can values of row not destination.name
for(var i=0;i<obj.length;i++){ console.log(row[obj.index]); }
output
test2 source2 undefined
solution question
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]); } }
Comments
Post a Comment