0

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);
2
  • 1
    You're checking ele.key, not ele[key]. Since that field doesn't exist, it will never find a match. Commented May 19, 2022 at 20:11
  • ele.key doesn't exist on shoes array Commented May 19, 2022 at 20:14

2 Answers 2

5

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);
//                                  ^   ^
Sign up to request clarification or add additional context in comments.

Comments

1

Replace ele.key to ele[key]

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.