Skip to content Skip to sidebar Skip to footer

Json - Javascript - How To Search Array Item By Searching List Of Values

I have json array is as below [ { French: 'Hello', Spanish: 'Hello1', english:'Hello2' },{ French: 'Hello3', Spanish: 'Hello4',

Solution 1:

You can try this:

function findIndex(arr, str) {
    for (var i = 0; i < arr.length; i++) {
        for (var key in arr[i]) {
            if (arr[i][key] === str) {
                if (arr[i].hasOwnProperty(key) {
                    return arr[i];
                }
            }
        }
    }
    return null;
}

This method consists of an array search with a normal for loop and then, for each element of this array, we perform a for..in loop.


Solution 2:

Here is my sample using native functions:

var items = [/*your sample*/];
var myValue = "Hello6";

var result = items.filter(function (item) { 
    return Object.keys(item).some(function (property) { 
        return item[property] === myValue; 
    });
});

Solution 3:

you can use filter function:

var val = "Hello6";
//if you want to filter the array
resultArray = jsonArray.filter(function(obj, index){
    for(var key in obj){
        if(obj[key]==val) return obj;
    }
});

var indexes=[];
//if you want to find the results
jsonArray.forEach(function(obj, index){
    for(var key in obj){
        if(obj[key]==val){
            indexes.push(index);
            break;
        }
    }
});

Post a Comment for "Json - Javascript - How To Search Array Item By Searching List Of Values"