从具有子键值的 JSON 文件中获取密钥

huangapple go评论55阅读模式
英文:

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 = {&quot;a&quot;:{&quot;category&quot;:&quot;Drama&quot;},&quot;b&quot;:{&quot;category&quot;:&quot;Adventure&quot;},&quot;c&quot;:{&quot;category&quot;:&quot;Drama&quot;}};

const dramaKeys = Object.entries(obj).reduce((keys, [key, { category }]) =&gt; {
  if (category === &quot;Drama&quot;) {
    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 }]) =&gt; category === &quot;Drama&quot;)
  .map(([key]) =&gt; key);

huangapple
  • 本文由 发表于 2023年3月7日 11:12:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定