Trying to see if object key exists keep getting undefined

Viewed 64

I have a data response that responds with different objects in an array.

I have tried a variety of different methods to determine if the key 'name' exists including:

const hasName = array.forEach(item => "name" in item )

const hasName = array.forEach(item => Object.keys(item).includes('name') )

const hasName = array[0].hasOwnProperty("name") ? true : null

const hasName = array => array.some(x => x.some(({ name }) => name));

// lodash 'has' method
const hasName = has(array, 'name')

Array1 returns objects like:

[
  {
   name: 'cool name'
  }
]

Array2 returns objects like:

[
  {
   group: 'cool group'
  }
]

All of the methods I tried have either returned undefined or nothing at all and I'm completely at a loss for why. I have scoured Stack Overflow and the internet trying to get a better direction or an answer but I haven't been able to find anything.

3 Answers

You're not returning anything from some of your calls on the array. forEach for example runs a callback, and always returns undefined see docs. Your code just isn't working because you're using the functions incorrectly.

The code below filters your array to get the elements with a name property, then counts them to see whether one or more exists, which results in a true or false being stored in the hasName variable.

let myArr = [
  {
   name: 'cool name'
  }
]

const hasName = 
  myArr
    .filter(a => a.hasOwnProperty("name")) // filter for elements in the array which have a name property
    .length // get the number of filtered elements
    > 0 // check whether the number of elements in array with name prop is more than 0


console.log(hasName)

If you are sure that the "response" is fully received before the check, THEN
Your latest variant of the check can be implemented as follows:

array.some(obj => (obj.name !== undefined)); // fast, but not define .name if it is "undefined"
array.some(obj => obj.hasOwnProperty("name")); // slower, but will define .name with any value

Your solutions are generally correct, but it looks like you're a little confused,

Array.forEach always returns "undefined":

array.forEach(obj => {
    console.log("name" in obj); // true for 1st array
    console.log("group" in obj); // true for 2nd array
}); // return "undefined"

array[0].hasOwnProperty() works fine, and can't return "undefined" at all.

console.log(
    array[0].hasOwnProperty("name") ? true : null; // return ("true" for the 1st array) AND ("null" for the 2nd)
);

When you used the Lodash, maybe you forgot to point to the object index?

_.has(array[0], 'name'); // return ("true" for the 1st array) AND ("false" for the 2nd)

Try a for loop

for (var i = 0; i < array.length; i++) {
    if (array[i].hasOwnProperty('name')) {
        console.log(array[i].name); //do something here.
        break;
    }
}
Related