我有以下对象:
{
"Size": {
"L": [
"Men clothing",
"Women clothing",
"Toys"
],
"M": [
"Women clothing"
]
}
}
我正在尝试创建一个函数,该函数返回包含给定类别的大小键。
例如,当我传递Men clothing
时,我需要期望函数返回["L"]
。我通过Men clothing
和Women clothing
,我需要结果为["L", "M"]
。
答案 0 :(得分:0)
有多种方法来获取包含给定字符串的键。这是其中之一:
const collection = {
"Size": {
"L": [
"Men clothing",
"Women clothing",
"Toys"
],
"M": [
"Women clothing"
]
}
}
function getSizes(obj, categories) {
return Object.keys(obj).filter(key => {
return categories.some(category => obj[key].includes(category));
});
}
console.log(getSizes(collection.Size, ['Men clothing']));
console.log(getSizes(collection.Size, ['Men clothing', 'Women clothing']));