简体   繁体   中英

How can I access an object in an array based on the value of a specific key?

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?

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.

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

function:

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

javascript array docs

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']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM