learningToCode
learningToCode

Reputation: 1

Accessing array inside javascript object

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;
};

Upvotes: 0

Views: 49

Answers (2)

Kieran E
Kieran E

Reputation: 3666

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))

Upvotes: 1

yBrodsky
yBrodsky

Reputation: 5041

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']

Upvotes: 0

Related Questions