- 此问题在此处已有答案**:
Find object by id in an array of JavaScript objects(36个答案)
昨天关门了。
下面是我正在使用的一个类似数组的示例:
const characters = [
{
"id": 0,
"name": "Amelia Bedelia",
"bio": "Amelia Bedelia is children's book based on a silly, silly girl. ",
"wikipedia": "http://en.wikipedia.org/wiki/amelia_bedelia",
"books": 193
},
{
"id": 1,
"name": "Ronald McDonald",
"bio": "Ronald McDonald is the fast food king. He is also a clown",
"wikipedia": "http://en.wikipedia.org/wiki/ronald_mcdonald",
"books": 88
},
{
"id": 2,
"name": "Cookie Monster",
"bio": "Cookie Monster Lives on Sesame Street. He loves Cookies",
"wikipedia": "http://en.wikipedia.org/wiki/cookie_monster",
"books": 70
},
{
"id": 3,
"name": "Scooby Doo",
"bio": "Scooby Doo is a dog. He solves mysteries and loves junk food.",
"wikipedia": "http://en.wikipedia.org/wiki/scooby_doo",
"books": 73
},
]
假设我想使用函数characterBio(array,name)作为一个参数来返回我选择作为字符串输入到函数中的任何名字的bio,我该怎么做呢?
这是我到目前为止所做的,但是它给了我所有bios的输出,我不知道如何让它只返回我选择的任何人的一个bios。
function characterBio(array,name){
for (characters.name in characters){
const selectedBio = characters.map((artists) => ({
bio : characters.bio
}))
console.log(selectedBio);
}
}
characterBio(characters,'Cookie Monster');
例如,如果我要做:
第一个月
我该如何修改这段代码以只返回饼干怪物的生物。
我试过这个
function characterBio(array,name){
for (characters.name in characters){
const selectedBio = characters.map((artists) => ({
bio : characters.bio
}))
console.log(selectedBio);
}
}
characterBio(characters,'Cookie Monster');
但我不知道如何修改它只做一个生物的人,我选择。
1条答案
按热度按时间j0pj023g1#
.filter()
数组中的每个对象Object.values()
提取一个值数组.includes()
在该值数组中查找匹配项。.filter()
将提取整个对象作为返回