3

I have an array of objects:

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

I want to check if an object with a certain value for property a exists. If this exists then it should return the value of property b.
The value of a is always unique.

For example, if I am looking for "11", then it should return "Test1".

Darryl Noakes
  • 2,207
  • 1
  • 9
  • 27
Divya
  • 107
  • 1
  • 1
  • 7

7 Answers7

8

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 => x.a == 11).b)
// Test1

You should take care to handle the case when the queried item is not found, otherwise it's easy to encounter null/undefined errors -

const data = [
  {"a": "11", "b":"Test1"},
  {"a": "22", "b":"Test2"},
  {"a": "33", "b":"Test1"},
  {"a": "44", "b":"Test3"},
]

const result = data.find(x => x.a == 11)

if (result == null)
  console.log("not found")
else
  console.log(result.b) // Test1
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • @DarrylNoakes thanks for the edit but your broke the program – Mulan Jul 17 '23 at 16:21
  • Oh. _Why_ are you using loose comparison and comparing with a number, instead of just using a string? – Darryl Noakes Jul 17 '23 at 16:24
  • Other than that, would you consider my edit acceptable? Still learning the "etiquette" around editing others' answers. – Darryl Noakes Jul 17 '23 at 16:25
  • 1
    no worries. i always welcome edits, other users may differ. one thing i would strongly suggest is if an answer contains a code snippet, your edits should not change the meaning/output of the program. an exception to that is a bug. feel free to change it to `... === "11"` if you prefer. i didn't draw attention to that as it's not relevant for how `find` works. – Mulan Jul 17 '23 at 17:50
2

Considering that you'll have same predefined properties a & b in your object, you can simply use find for your purpose. The following example demonstrates how you can use find method over an array of objects -

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

// This will return the value of b if exists else undefined
const newArrObj = arrObj.find(obj => obj.a === "11")?.b;

console.log(newArrObj);
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
2

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)
brk
  • 48,835
  • 10
  • 56
  • 78
0

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");
Nhat Nam
  • 21
  • 2
0

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]);
        }
    });
});
Sang Anh
  • 11
  • 2
0

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))
nsbrown
  • 55
  • 12
-1

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.

Geek
  • 2,766
  • 1
  • 19
  • 16