【问题标题】:Categorise JSON Data [closed]对 JSON 数据进行分类 [关闭]
【发布时间】:2021-08-23 01:43:11
【问题描述】:

嘿,请不要烤我。所以我有一个这样的 JSON 数据

data": {
    "person": [
      {
        "id": "xx1",
        "name": "John DOe",
      },
     ],
    "person": [
      {
        "id": "xx2",
        "name": "John Snow",
      },
     ],
}

例如,我想存储名称中包含“o”的每个人的数据。我怎么能那样做?谢谢

【问题讨论】:

  • 使用array.filter函数
  • SO 不是代码编写服务,您已经尝试过什么?您对样本输入的预期结果是什么?顺便说一句,我认为您的 data 不是有效对象,您重复了 person 键。

标签: javascript json reactjs graphql


【解决方案1】:

JSON 对象,如果有重复的键,它会将第一个替换为最底部的一个。

在您的示例数据中,有两个“人”键。因此,最终,您所说的数据将屈服于此。

{"data":{"person":[{"id":"xx2","name":"John Snow"}]}}

因此,为了澄清您的数据,恕我直言,首先应该是这样的。

"data": {
    "person": [
      {
        "id": "xx1",
        "name": "John DOe",
      },
      {
        "id": "xx2",
        "name": "John Snow",
      },
     ]
}

然后您可以将data.person 视为一个数组,并使用Array.prototype 函数将filter 取出您想要的详细信息。

过滤方法应该是

const personWithNameO = data.person.filter((v) => v.name.includes("o") );
console.log(personWithNameO);

【讨论】:

  • 非常感谢!你真的帮助我的人:) 希望你有一个美好的生活
猜你喜欢
  • 2013-03-30
  • 2013-01-18
  • 2023-01-15
  • 2013-11-25
  • 2019-02-19
  • 2014-02-05
  • 2020-02-09
  • 2011-12-13
  • 2020-03-23
相关资源
最近更新 更多