英文:
Getting the key from a json file with subkey value
问题
可以有人告诉我如何使用子键值获取 JSON 文件的 main_key 吗?例如:
所以我想检索所有包含 'Drama' 作为 category 值的主键。
英文:
Can someone tell me how to get the main_key of a json file using sub_key values.. for example
{
"a": {
"category": "Drama"
},
"b": {
"category": "Adventure",
},
"c": {
"category": "Drama"
}
}
So i want to retrieve all the main keys contains 'Drama' as value of category.
Can You explain the functions in easy wat as u help.
答案1
得分: 3
使用Object.entries()获取键/值对的数组,然后通过检查每个值的category
属性,使用reduce将其减少为键的数组
const obj = {"a":{"category":"Drama"},"b":{"category":"Adventure"},"c":{"category":"Drama"}};
const dramaKeys = Object.entries(obj).reduce((keys, [key, { category }]) => {
if (category === "Drama") {
keys.push(key);
}
return keys;
}, []);
console.log(dramaKeys);
您还可以使用_filter_和_map_来实现相同的效果
const dramaKeys = Object.entries(obj)
.filter(([, { category }]) => category === "Drama")
.map(([key]) => key);
英文:
Use Object.entries() to get an array of key / value pairs then reduce that to an array of keys by checking the category
property of each value
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const obj = {"a":{"category":"Drama"},"b":{"category":"Adventure"},"c":{"category":"Drama"}};
const dramaKeys = Object.entries(obj).reduce((keys, [key, { category }]) => {
if (category === "Drama") {
keys.push(key);
}
return keys;
}, []);
console.log(dramaKeys);
<!-- end snippet -->
You could also use a filter and map for the same effect
const dramaKeys = Object.entries(obj)
.filter(([, { category }]) => category === "Drama")
.map(([key]) => key);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论