亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅提取數組中的多個對象

僅提取數組中的多個對象

牛魔王的故事 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 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號