【问题标题】:Angular extract data from JSON corresponding to Key从对应于 Key 的 JSON 角度提取数据
【发布时间】:2021-01-11 17:55:43
【问题描述】:

以下是我从服务器收到的 JSON。 现在我有变量public checkId: any = 54

如何从JSON下面提取ID = 54对应的数据??

我想提取下面提到的针对 KEY 54

"Increase Again": true,
 "Decrease Previous" : true,
 "Like" : true,
 "Dislike" : true,
 "Old Again" : false,
 "Others" : true

以下是我必须从中提取上述数据的 JSON

{
"27" : { 
 "Increase": true,
 "Decrease" : true,
 "Like" : true,
 "Dislike" : true,
 "Old" : false,
 "Others" : true
},
"54" : { 
 "Increase Again": true,
 "Decrease Previous" : true,
 "Like" : true,
 "Dislike" : true,
 "Old Again" : false,
 "Others" : true
},
"104" : { 
 "Increase Previous": true,
 "Decrease Prior" : true,
 "Like" : true,
 "Dislike" : true,
 "Old" : false,
 "Others Check" : true
  }
}

提前致谢...

#Edit - 关键不只是 1,2,3 它们是特定的 ID 53,54,55 也可以是 100, 108, 4657

【问题讨论】:

  • 由于 ID 是键,假设 API 中的对象分配给 response 变量,您可以简单地执行 response[this.checkId]
  • @MichaelD - 我已经对响应进行了编辑,密钥不是 1、2、3,它可以是任何数字。在那种情况下,你的解决方案会起作用吗??
  • 我不明白为什么不这样做。从应用程序的角度来看,b/n 2 或 54 或任何其他数字没有区别。只要该属性可用,它将返回一个有效对象。如果它不可用,它将返回undefined

标签: javascript arrays json angular typescript


【解决方案1】:

您可以通过在响应中传递 checkId 来简单地获取特定元素,例如,我假设您在结果变量中有该 JSON。

你可以通过以下方式调用它

 let result = //Your json;
 let checkId = 2;
 result[checkId] ==> This will return 2nd object of JSON

【讨论】:

  • 我已经对响应进行了编辑,密钥不是 1、2、3,它可以是任何数字。在那种情况下,你的解决方案会起作用吗??
  • 你是说你会有动态键?
  • 是的,根据服务器将返回的特定条件,它可以是任何数字,因此我将拥有我的变量 checkID
  • 如果您在 checkID 变量中设置了值,此方法将起作用。但是如果您不知道 checkID 的值,我们可以遍历 JSON 数据以获得您想要的结果。
【解决方案2】:

您可以像这样简单地获得 Ur Desired Value..

let checkId = 2;
let data = {
    "1": {
        "Increase": true,
        "Decrease": true,
        "Like": true,
        "Dislike": true,
        "Old": false,
        "Others": true
    },
    "2": {
        "Increase Again": true,
        "Decrease Previous": true,
        "Like": true,
        "Dislike": true,
        "Old Again": false,
        "Others": true
    },
    "3": {
        "Increase Previous": true,
        "Decrease Prior": true,
        "Like": true,
        "Dislike": true,
        "Old": false,
        "Others Check": true
    }
}
let result = data[checkId]
console.log(result)

【讨论】:

  • 我已经对响应进行了编辑,密钥不是 1、2、3,它可以是任何数字。在那种情况下,你的解决方案会起作用吗??
  • @Rose - 这行得通。如果您只想提取密钥,请尝试以下代码 Object.keys(this.data)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-23
相关资源
最近更新 更多