【问题标题】:get index from a JSON object with value in postman/newman从带有 postman/newman 值的 JSON 对象获取索引
【发布时间】:2018-05-06 02:32:07
【问题描述】:

我正在尝试通过传递值的引用来检索索引。

我有一些 javascript 选项,但所有这些函数都显示 is not a function

出现如下错误:

TypeError | jsonData.getIndexOf is not a function

我已经尝试过以下链接中提到的选项:

get index from a JSON object with value

例子:

var jsonData = JSON.parse(responseBody);

Array.prototype.getIndexOf = function(el) {

  var arr = this;

  for (var i=0; i<arr.length; i++){
     console.log(arr[i].name);
     if(arr[i].name==el){
       return i;
     }

  }

  return -1;

}

console.log(jsonData.getIndexOf("Volume"));

对象截图:

邮递员/纽曼是否可以

【问题讨论】:

  • 你能发布一些来自responseBody 的数据吗?
  • console.log(jsonData instanceof Array) 的输出是什么?
  • 我不能按照规则准确地发布我的回复。但是那个 JSON 是巨大的,有这么多的键和嵌套数组等。
  • JSON 对象最有可能具有字母数字键并被转换为对象而不是数组。您可能还需要扩展对象原型
  • @ShubhamJain — “但是 JSON 很大” — 这就是为什么你需要构造一个 minimal reproducible example

标签: javascript postman newman


【解决方案1】:

我成功使用了这个更新的代码:

var jsonData = JSON.parse(responseBody);

//I would use an Object prototype here, because jsonData is an object
Object.prototype.getIndexOf = function(el) {
  var arr = this;
  
  for (var i=0; i<arr.length; i++){
      //when you're checking to see if a key exists, it is better to use the "in" operator
     if(el in arr[i]){
       return i;
     }
  }

  return -1;
}

//make sure the case matches
console.log(jsonData.getIndexOf("Volume"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 2023-03-15
    • 2019-04-03
    • 2013-01-25
    • 1970-01-01
    相关资源
    最近更新 更多