I have below array of objects. I want to check what errorCode value is present in objArray
.
JavaScript
x
11
11
1
var objArr = [
2
{
3
"7364234": "hsjd",
4
"errorCode": "400"
5
},
6
{
7
"12345": "jd",
8
"errorCode": "500-001"
9
}
10
]
11
Below is the solution that finds the key errorCode
is present in an array of objects or not. If I do a console.log as shown below, I get the desired results.
JavaScript
1
10
10
1
const contains = (string) =>
2
objArr.findIndex(
3
// Is the string contained in the object keys?
4
obj => Object.keys(obj).includes(string)
5
) !== -1
6
7
console.log(contains('errorCode')) // returns true
8
console.log(contains('spaghetti')) // returns false
9
10
But I want to know what value of errorCode is present in the objArray
. for e.g. i want to find out if errorCode: "500-001"
is present in objArray
. How can I get this result? Can someone please suggest?
Advertisement
Answer
You can use Array.prototype.some
as follows.
JavaScript
1
13
13
1
var objArr = [
2
{
3
"7364234": "hsjd",
4
"errorCode": "400"
5
},
6
{
7
"12345": "jd",
8
"errorCode": "500-001"
9
}
10
];
11
12
const contains = (keyVal) => objArr.some(({ errorCode }) => errorCode.includes(keyVal));
13
console.log(contains("500"));