简体   繁体   中英

Javascript: How to check if a value exists in an object

I have an array of object

var arrObj=[
            {"a" : "11", "b":"Test1"},
            {"a" : "22", "b":"Test2"},
            {"a" : "33", "b":"Test1"},
            {"a" : "44", "b":"Test3"}
           ];

I want to check if "11" exists in the object. If this exists then it should return the value of key "b" ie "Test1". The value in key "a" is always unique.

Array.prototype.find is exactly what you're looking for – it's better than Array.prototype.filter in this case because it will stop iterating as soon as the first match is found

 const data = [ {"a" : "11", "b":"Test1"}, {"a" : "22", "b":"Test2"}, {"a" : "33", "b":"Test1"}, {"a" : "44", "b":"Test3"} ] console.log (data.find(x => xa == 11).b) // Test1 

This code will filter your array.

 var arrObj=[ {"a" : "11", "b":"Test1"}, {"a" : "22", "b":"Test2"}, {"a" : "33", "b":"Test1"}, {"a" : "44", "b":"Test3"} ]; var newArrObj = arrObj.filter(function(obj) { return obj.a == 11; }) console.log(newArrObj); 

There can be multiple solution to this problem, using only array methods. Methods like filter , find , findIndex can be used.

Below is a snippet of using findIndex . It will return the index of the object if the element exist in array, if not it will return -1

 var arrObj = [{ "a": "11", "b": "Test1" }, { "a": "22", "b": "Test2" }, { "a": "33", "b": "Test1" }, { "a": "44", "b": "Test3" } ]; var m = arrObj.findIndex(function(item) { return item.a === "11"; }); console.log(m) 

I hope this code is what you want:

var checkAndReturn =function (arr, n){
        for(let i = 0; i < arr.length; i++){
            if(arr[i]["a"] === n) return arr[i]["b"];
        }
}

Use it:

checkAndReturn(arrObj, "11");

just only use looping and check, hope this code is work for you!

arrObj.forEach(function(a) {
    a = Object.keys(a).map(function(key){
        return a[key];
    });

    a.forEach(function(v2, k2, d){

        if(d[0] == 11) {
            console.log(d[1]);
        }
    });
});

You can make it a one-liner with arrow functions.

 var arrObj=[ {"a": "11", "b":"Test1"}, {"a": "22", "b":"Test2"}, {"a": "33", "b":"Test1"}, {"a": "44", "b":"Test3"} ]; console.log(arrObj.filter(obj => obj.a == 11))

This is a possible duplicate of Find object by id in an array of JavaScript objects

So,looking at that thread, this should do it for you.

var result = $.grep(arrObj, function(e){ return e.a == '11'; });
console.log(result[0].b);

You can make a function for first line and call it passing the Id you are looking for.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM