user3257884
user3257884

Reputation: 1

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',
        english:'Hello5'
    },{
        French: 'Hello6',
        Spanish: 'Hello7',
        english:'Hello8'
    },{
        French: 'Hello9',
        Spanish: 'Hello10',
        english:'Hello81'
    }
];

In Javascript array If I wanted to search items based on values

ex If I give Hello6 as finding string I should get 3rd item in the list. I would like generic search rather searching each and every element.

Upvotes: 0

Views: 144

Answers (4)

Dalorzo
Dalorzo

Reputation: 20024

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

Upvotes: 1

user1636522
user1636522

Reputation:

You could use good old for loops :

function find(array, fn) {
    for (var i = 0, l = array.length; i < l; i++) {
        if (fn(array[i]) === true) return array[i];
    }
}

Usage example :

var a = [{ a: 1 }, { a: 2 }, { a: 3 }];
var result = find(a, function (item) {
    return item.a === 2;
});
result; // { a: 2 }

With a more complex array :

var a = [
    { a: 1, b: 2 }, 
    { a: 3, b: 4 }, 
    { a: 5, b: 6 }
];
var result = find(a, function (item) {
    for (var k in item) {
        if (item[k] === 4) return true;
    }
});
result; // { a: 3, b: 4 }

Upvotes: 0

Mehran Hatami
Mehran Hatami

Reputation: 12961

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

Upvotes: 0

Danilo Valente
Danilo Valente

Reputation: 11352

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.

Upvotes: 2

Related Questions