Skip to content
Advertisement

Find property value in array of objects (Javascript)

I have below array of objects. I want to check what errorCode value is present in objArray.

var objArr = [
  {
  "7364234": "hsjd",
  "errorCode": "400"
  },
  {
  "12345": "jd",
  "errorCode": "500-001"
  }
]

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.

const contains = (string) =>
  objArr.findIndex(
    // Is the string contained in the object keys?
    obj => Object.keys(obj).includes(string)
  ) !== -1

console.log(contains('errorCode')) // returns true
console.log(contains('spaghetti')) // returns false

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.

var objArr = [
  {
  "7364234": "hsjd",
  "errorCode": "400"
  },
  {
  "12345": "jd",
  "errorCode": "500-001"
  }
];

const contains = (keyVal) => objArr.some(({ errorCode }) => errorCode.includes(keyVal));
console.log(contains("500"));
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement