0

I am so ashamed of asking such a basic thing but I have been trying to work it out for a long time now and I cannot figure it out :(

I have two arrays. One contains keys and the other values.

I have combined them so I can have one array with the key value pair:

var combinedArray = [];
var keysArray = [];
var valuesArray = [];
keysArray = ["LND", "NY", "MAD"];
valuesArray = ["London", "New York", "Madrid"];
var keysArrayLength = keysArray.length;

for (var i = 0; i < keysArrayLength; i++) 
{  
 combinedArray.push({
 key: keysArray[i],
 value: valuesArray[i]
 });  
}

Now I need to get the value of a certain key.

For example, I want to have in a variable the value of key "LND"

So I do:

var result = $.grep(combinedArray, function(e){ return e.key == 'LND'; });

But in result, I get a [Object, Object] instead of London

What am I doing wrong?

Thanks!

3 Answers 3

1

$.grep will return to you an array, which consists of objects (which has key and value fields). So to get value you can use:

var result = $.grep(combinedArray, function(e){ return e.key == 'LND'; });
alert(result[0].value);

Fiddle.

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

Comments

0

From the documentation

The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test

meaning that the result is an array containing the object that matches your filter (is this case the key)

So you'll get it as you normally do from an array result[0].value

var combinedArray = [];
var keysArray = [];
var valuesArray = [];
keysArray = ["LND", "NY", "MAD"];
valuesArray = ["London", "New York", "Madrid"];
var keysArrayLength = keysArray.length;

for (var i = 0; i < keysArrayLength; i++){  
   combinedArray.push({
      key: keysArray[i],
      value: valuesArray[i]
   });  
}

var result = $.grep(combinedArray, function(e){ return e.key === 'LND'; });

document.write(result[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Comments

0

.grep creates array you must use this kind of code

var combinedArray = [];
var keysArray = [];
var valuesArray = [];
keysArray = ["LND", "NY", "MAD"];
valuesArray = ["London", "New York", "Madrid"];
var keysArrayLength = keysArray.length;

for (var i = 0; i < keysArrayLength; i++) 
{  
 combinedArray.push({
 key: keysArray[i],
 value: valuesArray[i]
 });  
}

var result = $.grep(combinedArray, function(e){ return e.key == 'LND'; });

console.log(combinedArray);
alert(result[0].value);

Example http://jsfiddle.net/6hza5m5e/1/

Comments

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.