I'm trying to return an array of values based on a key. The values I am trying to return is dependent on the key a user enters. However, when I am iterating through my for loop I am getting an error saying: TypeError: Cannot read property 'length' of undefined
. What am I doing wrong?
var obj = {
14: ['abc', 'def', 'gh', 'i', 'k'],
90: ['asdf','xxc' , 'd'],
92: ['def', 'dr' , 'vvd', 'off']
}
exports.function(key) = {
var temp = {};
for(var i = 0; i < obj.key.length; i++){
temp[i] = obj.key[i];
}
return temp;
};
Like I said in my comment, object.key
is looking for an attribute literally called key
. If you want to access an attribute that is defined by a user's input, you have to use the []
syntax. In your case, [key]
.
Try this:
exports.function(key) = {
return obj[key];
};
Or, in snippit form,
var obj = { 14: ['abc', 'def', 'gh', 'i', 'k'], 90: ['asdf','xxc' , 'd'], 92: ['def', 'dr' , 'vvd', 'off'] }; function getKey(key){ return obj[key]; } console.log(getKey(14)) console.log(getKey(92))
If I understood correctly:
var obj = {
14: ['abc', 'def', 'gh', 'i', 'k'],
90: ['asdf','xxc' , 'd'],
92: ['def', 'dr' , 'vvd', 'off']
}
function test(key) = {
return obj[key];
};
test(14) //returns ['abc', 'def', 'gh', 'i', 'k']
test(92) //returns ['def', 'dr' , 'vvd', 'off']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.