-1

I have this object/array of objects.

const products = [{
    name: 'apple',
    count: 3
}, {
    name: 'banana',
    count: 5
}, {
    name: 'carrot',
    count: 2
}, ]

I want to return a specific object based on the value of a specific key (in this case 'name').

const getObj = (nameToFind) => {
    for (let n of products) {
        if (n.name == nameToFind) {
            return n
        }
    }
}

console.log(getObj('banana'))
// { name: 'banana', count: 5 } 

Is there a better way to do this, without a for loop and if statement?

  • 1
    Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – pilchard Nov 22 '20 at 02:06
  • [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+find+object+by+value+of+property) of [Get JavaScript object from array of objects by value of property](https://stackoverflow.com/q/13964155/4642212). – Sebastian Simon Nov 22 '20 at 02:17

3 Answers3

2

Yes, use array.prototype.find

const products = [{
    name: 'apple',
    count: 3
}, {
    name: 'banana',
    count: 5
}, {
    name: 'carrot',
    count: 2
}, ]

const answer = products.find(x => x.name === "apple" )

console.log(answer)

Similarly, use array.prototype.filter if you want to get multiple elements, find will return the first result it manages to get.

tsamridh86
  • 1,480
  • 11
  • 23
  • Note that `find` returns one element; if there's more than one that matches the search, it returns the first. If there might be more than one and you want to return them all, use `filter` instead - it always returns an array, even if only one match is found. – Mark Reed Nov 22 '20 at 02:10
0

products.find((product) => product.name === 'apple')

function:

const findObjectByProperty = (objectsArray, propName, value) => { return objectsArray.find((object) => object[propName] === value) }

javascript array docs

Michael Mudge
  • 369
  • 1
  • 5
  • 10
0
const products = [{
    name: 'apple',
    count: 3
},{
    name: 'banana',
    count: 5
}, {
    name: 'carrot',
    count: 2
}, ]

const createMap = (list, key) => list.reduce((map, item) => (map[item[key]] = item, map), {});

const map = createMap(products, 'name');

console.log(map['banana']);
    
console.log(map['apple']);

afcfzf
  • 29
  • 5