Home > Net >  Javascript arrow function vs anonymous function
Javascript arrow function vs anonymous function

Time:08-17

I was trying to write a function that takes in an array of objects and a string and returns a boolean telling you whether the string is a key in one of the elements of the array or not. These two ways look the same to me, however, only one of the works. The following code works:

function keyInObjectArray(objArray, keyString) {

  let arr = [];

  arr = objArray.filter(item => item[keyString] !== undefined);

return arr.length !== 0;

}

while this one doesn't work:

function keyInObjectArray(objArray, keyString) {
 // Your code here

 let arr = [];

 arr = objArray.filter(function (element) {return element[keyString] !== undefined});

return arr.length !== 0;

}

What am I missing here? How can I rewrite it using the second method?

CodePudding user response:

try this, rewrite using second method.

function keyObjectArray(objArray, keyString) { let arr = [];

arr = objArray.filter((element) => {
    return element[keyString] != undefined})
    return arr.length !== 0
}

CodePudding user response:

You are reinventing the wheel here, there is already a built-in method for that. Checkout Object.prototype.hasOwnProperty() it does exactly what you need.

const obj = {
  'one': 1,
  'two': 2
}
console.log(obj.hasOwnProperty('one'))   // true
console.log(obj.hasOwnProperty('two'))   // true
console.log(obj.hasOwnProperty('three')) // false

  • Related