问题描述:

I have json file that has surname has 1 value, first_name has 2 valuse in an array, and other object only has 1 value in array.

How will I be able to get the Jhon and Jason?

Here is my json file

[{

"surname": "Vlad",

"first_name": [

"Jhon",

"Jason"

],

"age": 25,

},

{

"surname": "Vlad",

"first_name": [

"Jhon",

],

"age": 25,

},

{

"surname": "Vlad",

"first_name": [

"Jhon",

"Jason"

],

"age": 25,

}

]

Here is my jquery/javascript code

 $.each(data, function (key, val){

var getNameValue = val.first_name;

if(getNameValue == getFirstName){

alert(getNameValue);

}

});

The value

getFirstName

is came from an search textbox to enter the surname or first_names.

When I search the word "Jhon" I only get the Array[1] which doesn't have any array inside the first_name.

I want to get all of them Indexes (0 1 2) when I search the word "Jhon".

网友答案:

Array[1] does have an array inside, it is only loose comparison that makes it evaluate in the way you are expecting. Also, you don't need the comma after the element if there are no other elements in that array. You can use Array.indexOf("nameYouAreLookingFor"), where Array is the variable holding your array. This will return -1 if it is not in the array.

网友答案:
$.each(data, function(i, item) {
    var firstNames = item.first_name;
    if ($.inArray(getFirstName, firstNames) != -1) {
        alert(getFirstName);
    };
});
相关阅读:
Top