Home > Enterprise >  using .find() method but get undefined in JavaScript
using .find() method but get undefined in JavaScript

Time:05-20

Here I'm defining a function using .find() method, and it should return { name: 'Adidas', price: 95 }.Anyone knows why it returns 'undefined' instead?

    var shoes = [
  { name: 'Nike', price: 200 },
  { name: 'Red Wings', price: 250 },
  { name: 'Vans', price: 150 },
  { name: 'Converse', price: 160 },
  { name: 'Reebok', price: 130 },
  { name: 'New Balance', price: 175 },
  { name: 'Adidas', price: 95 },
  { name: 'Keds', price: 140 },
  { name: 'Crocs', price: 135 }
];



const findWhere = function (array, criteria) {

  const key = Object.keys(criteria)[0];
  criteria = criteria[key];

  const result = array.find(ele => ele.key === criteria);
  return result;
};

const myShoe = findWhere(shoes, {price: 95});
console.log(myShoe);

CodePudding user response:

You've used ele.key which accesses the literal key property on ele.

And since there is no key property on any of these objects:

{ name: 'Crocs', price: 135 }

ele.key is always undefined, meaning you get no matches.

Use brackets like you had earlier (criteria = criteria[key];):

const result = array.find(ele => ele[key] === criteria);
//                                  ^   ^

CodePudding user response:

Replace ele.key to ele[key]

const result = array.find(ele => ele[key] === criteria);
  • Related