【问题标题】:JS, Loop over Json object list [duplicate]JS,循环Json对象列表[重复]
【发布时间】:2019-06-30 13:21:30
【问题描述】:

这是我使用console.log(res)得到的结果

{d: Array(4)}
d: Array(4)
0: {__type: "Claim_Inbox+SubClaims", Claim_detail: 12, Claim_id: 123, …}
1: {__type: "Claim_Inbox+SubClaims", Claim_detail: 12, Claim_id: 124, …}
2: {__type: "Claim_Inbox+SubClaims", Claim_detail: 12, Claim_id: 125, …}
3: {__type: "Claim_Inbox+SubClaims", Claim_detail: 12, Claim_id: 126,…}
length: 4
__proto__: Array(0)
__proto__: Object

使用以下代码,我得到了键列表:值

var counter = 0;
$.each(res.d[counter ], function (key, value) {
   console.log(key + ": " + value);
   counter++;
});

如何读取像 Claim_id 这样的特定值? 我可以使用Switch(),但也许还有其他方法

【问题讨论】:

标签: javascript json


【解决方案1】:

首先,它不是Object,而是Array。 其次,根据您的需要,您可以使用 forEach 循环遍历数组并使用 id 显示或分配或执行您需要的任何操作,或者使用 map 构造具有所选值的新数组。

const array = [
  { __type: "Claim_Inbox+SubClaims", Claim_detail: 12, Claim_id: 123 },
  { __type: "Claim_Inbox+SubClaims", Claim_detail: 12, Claim_id: 124 },
  { __type: "Claim_Inbox+SubClaims", Claim_detail: 12, Claim_id: 125 },
  { __type: "Claim_Inbox+SubClaims", Claim_detail: 12, Claim_id: 126 }
];

array.forEach(item => console.log(item['Claim_id']); );

console.log("--------------------");

// Generate a new array copy
const result = array.map(item => item['Claim_id']);

console.log(result)

【讨论】:

  • Array 是 JS 中的 Object
  • @fard 是的,它们是,但也是函数......不是因为你可以循环一个函数...... JavaScript 的基础是对象,但它们不是同一类型对象;)
  • 但是你不能说 Arrat 不是一个对象,就像你在第一句话中所做的那样@PrinceHernandez
猜你喜欢
  • 2016-06-22
  • 1970-01-01
  • 2010-10-22
  • 2021-10-30
  • 2019-05-25
  • 2017-01-23
  • 2018-04-26
  • 2019-11-26
  • 2020-02-16
相关资源
最近更新 更多