0

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;
};
3
  • 2
    Possible duplicate of Iterate through object properties Commented Apr 20, 2017 at 18:30
  • object.key is looking for an attribute literally called key. Try obj[key] instead Commented Apr 20, 2017 at 18:31
  • key is dependent on a user input, how can i access the array of values in this situation @KieranE Commented Apr 20, 2017 at 18:32

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

right, nvm my previous comment this is the correct way to do it
0

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

1 Comment

@OP this guy was definitely before me. But it really is that simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.