gpt4 book ai didi

javascript - 如果在对象中找到值,则返回键

转载 作者:行者123 更新时间:2023-11-30 09:11:25 25 4
gpt4 key购买 nike

有一个像这样的对象:

var animals = { "dog": ["black", "red", "green"],
"cat": ["pink", "red", "white"],
"bird": ["green", "grey", "yellow"]};

我想取回具有特定颜色的动物的名称,例如 "red" 我想返回一个包含 ["dog", "cat"的数组];尝试这样做,但我只返回 Array(0) 或 Array(1)

function findColor(animals, color) {

var result = [];
if (Object.values(animals).indexOf(color) > -1) {
result.push(color);
}

return result;
}

console.log(findColor(animals, "red"));

最佳答案

您可以简单地使用 Object.keysfilter

var animals = {
"dog": ["black", "red", "green"],
"cat": ["pink", "red", "white"],
"bird": ["green", "grey", "yellow"]
};

function findColor(animals, color) {
return Object.keys(animals).filter(key=>animals[key].includes(color))
}

console.log(findColor(animals, 'red'));


Why my code is not working ?

indexOf 使用严格比较,Object.values(animals) 返回一个二维数组,而您正试图将它与字符串值匹配,您需要做的是遍历键并在二维数组的子数组上使用 indexOf

var animals = {"dog": ["black", "red", "green"],"cat": ["pink", "red", "white"],"bird": ["green", "grey", "yellow"]};

function findColor(animals, color) {
var result = [];
Object.keys(animals).forEach(v => {
if (animals[v].indexOf(color) > -1) {
result.push(v)
}
})
return result;
}

console.log(findColor(animals, "red"));

关于javascript - 如果在对象中找到值,则返回键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58649182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com