简体   繁体   中英

How can I get a specific value from my JSON object without using Array.filter()?

Under rows , I want to check and see if I have a value of Submit and the integer value that comes after it. How can I retrieve these two values without using Array.filter()? Google Analytics JS api doesn't like the filter command.

{
  "rows": [
        [
      "Load",
      "11"
    ],
    [
      "No Thanks",
      "7"
    ],
    [
      "NoThanks",
      "3"
    ],
    [
      "No_Thanks",
      "2"
    ],
    [
      "Results",
      "88"
    ],
    [
      "Sent",
      "1"
    ],
    [
      "Sign Up",
      "9"
    ],
    [
      "XOut",
      "161"
    ],
    [
      "Submit",
      "30"
    ]
  ]
}

Just use a for loop...

var submitFound
for(var i = 0; i < rows.length; i++) {
  var row = rows[i]
  if (row[0] === 'Submit') {
    submitFound = true
    break
  }
}
if (submitFound) // do stuff

Assuming the structure you have in your question is assigned to returnData:

var returnedData = {...}; //Structure from the question
var value = -1;
for(var i = 0; i < returnedData.rows.length; i++){
    var row = returnedData.rows[i];
    if (row[0] == 'Submit') {
        value = row[1];
        break;
    }
}

if (value > -1) {
    // Do whatever with the value
}

Here is an alternative, if you don't wanna use a loop try this :

// this object is simplified for test

var json={
  "rows": [
        [
      "Load",
      "11"
    ],
    [
      "Submit",
      "30"
    ]
  ]
};

var stringJson=JSON.stringify(json);
var valueOfSubmit= stringJson.match("\"Submit\"\,\"([^)]+)\"\]")[1];
alert(valueOfSubmit);

Best regards

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