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".

7 Answers 7

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

Sign up to request clarification or add additional context in comments.

4 Comments

@DarrylNoakes thanks for the edit but your broke the program
Oh. Why are you using loose comparison and comparing with a number, instead of just using a string?
Other than that, would you consider my edit acceptable? Still learning the "etiquette" around editing others' answers.
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.
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)

Comments

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

1 Comment

Nah, you want Array.prototype.find instead
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");

Comments

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

Comments

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

Comments

-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.

1 Comment

Sorry, didn't see jQuery or $.grep mentioned anywhere

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.