为了账号安全,请及时绑定邮箱和手机立即绑定

仅提取数组中的多个对象

仅提取数组中的多个对象

牛魔王的故事 2023-08-18 14:18:17
我刚刚与 Postman 合作创建一些测试。大多数get响应由大块数组组成,其中包含大量对象(为了便于阅读,我只留下了两个属性,这些对象有 20 多个属性)。我有一个脚本可以读取整个响应以获取正确的数据,然后返回结果。如何在达到一定数量的对象时停止脚本?[   {      "username": "",      "active": ""   },   {      "username": "",      "active": ""   }]
查看完整描述

2 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

也许这对你有帮助(我不知道我是否理解得很好)。


但是使用filter您可以获取具有一个属性的值(您可以匹配您想要的任何内容)并且使用slice您将获得前 N 个值。


因此,您不必迭代整个列表,而可以仅检查这些值。


另外,如果您只想要匹配某个条件的元素数量,则只需要使用filter和 length 。


var array = [

   {

      "username": "1",

      "active": true

   },

   {

      "username": "2",

      "active": false

   },

   {

      "username": "3",

      "active": true

   }

]


var total = 1 // total documents you want

var newArray = array.filter(e => e.active).slice(0, total);


console.log(newArray)


//To know the length of elements that match the condition:

var length = array.filter(e => e.active).length

console.log(length)


查看完整回答
反对 回复 2023-08-18
?
倚天杖

TA贡献1828条经验 获得超3个赞

看看下面的代码是否有帮助


function processLongArray() {


  var myLongArray = [{

    "username": "active"

  }, {

    "username": "active"

  }, {

    "username": "inactive"

  }]; // and many more elements in the array


  var count = 0;

  var targetCount = 1; // stop after this number of objects

  for (var i = 0; i < myLongArray.length; i++) {

    var arrayItem = myLongArray[i];


    // condition to test if the arrayItem is considered in count

    // If no condition needed, we can directly increment the count

    if (arrayItem.username === "active") {

      count++;

    }


    if (count >= targetCount) {

      console.log("OK we are done! @ " + count);

      return count; // or any other desired value

    }

  }

}


processLongArray();


查看完整回答
反对 回复 2023-08-18
  • 2 回答
  • 0 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信