简体   繁体   中英

Extract only a number of objects within an array

I am freshly working with Postman to create some tests.

Most of the get responses consist of big chunks of arrays with lots of objects in them (I just left two properties for ease of read, the objects have 20+ properties).

I have a script that reads through the entire response for the correct data and then it returns the result.

How can I stop the script at a certain number of objects?

[
   {
      "username": "",
      "active": ""
   },
   {
      "username": "",
      "active": ""
   }
]

See if the below code helps

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();

Maybe this helps you (I don't know if I've understand well).

But using filter you can get the values with one property (you can match whatever you want) and using slice you will get the first N values.

So you don't have to iterate over the entire list and you can chech only these values.

Also, if you want only the number of elements that match a condition, only need to use filter and 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM