简体   繁体   English

如何根据特定键的值访问数组中的对象?

[英]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?有没有更好的方法来做到这一点,没有 for 循环和 if 语句?

Yes, use array.prototype.find是的,使用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.类似地,如果要获取多个元素,请使用array.prototype.filterfind将返回它设法获取的第一个结果。

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

function:功能:

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

javascript array docs javascript 数组文档

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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