1

I have a JSON array returned via ajax that looks like:

"stuff": [["2","66%"], ["3","42%"],...

Problem I want to match the zeroth index of each element in this array to a variable outside of the loop and if it matches, I want to return the percentage next to it.

I don't know the syntax in jQuery for this. Please have a look at my code below and see if that's correct or not:

var percentage = 0;
var stuffarr = jsonobj['stuff'];
var stuffID = jsonobj['stuff_id']
if (!stuffID || 0 === stuffID.length){
   $("#stuff-element").html("--");
}
else {
   var percentage = $.each(stuffarr, function (index, value) {
   if(value[0] == stuffID)
      return value[1]   
   });
}
2
  • What is var stuffID = jsonobj['stuff_id']. Is this another array? Commented Aug 31, 2017 at 9:56
  • It's a string number, e.g. "2" Commented Aug 31, 2017 at 9:56

3 Answers 3

2

Firstly, a bit of terminology. The data structure you have is an Object which holds several properties. It has nothing to do with JSON after it has been deserialised.

With regard to your issue, there's no jQuery required as you can use find() to find the item in the array by the stuffID variable's value. Try this:

var obj = {
  "stuff": [
    ["2", "66%"],
    ["3", "42%"]
  ],
  "stuff_id": "3"
}

var percentage = 0;
var stuffArr = obj['stuff'];
var stuffId = obj['stuff_id']

if (!stuffId || 0 === stuffId.length) {
  $("#stuff-element").html("--");
} else {
  percentage = stuffArr.find(function(el) {
    return el[0] == stuffId;
  })[1];
}
  
console.log(percentage);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

4 Comments

You could use the find method as you only want to return one
@LiverpoolOwen you're right - thanks. I'd misread the question and though the OP would possibly be searching for multiple.
Also, my bad but I think I shouldn't have re-initialised the percentage variable inside the else statement
@omrakhur yep, you should only define var percentage at the outer scope. I missed that too. Having a slow morning :)
1

try this

var percentage = stuffarr.find(function (value) {
if(value[0] == stuffID)
   return value[1];  
})[1];

2 Comments

Owen, your answer works fine as well, however Rory added a bit of an explanation, so I have accepted that as the correct one. Thank you.
That is fair enough
0

The return statement you used returns the result of the function(..) inside the .each(..) function and is not the return value of the .each(..) function. the valid return value is boolean which 'tells' the .each(..) function whether it should continue or not. instead use the following syntax:

var ret = '';
$(arr).each(function () {
    var curr = $(this);
    //console.log(curr); 
    if(curr[0] == stuffID){
        //console.log('>>found: ' + curr[1]);
        ret = curr[1];
        //if found -> break loop
        return false; 
    }
});

comment: you should consider instead of using an inner array data structure use an object, this is a more 'correct' data structure:

// "stuff": [{"id":"2","percent":"66%"}, {"id":"3","percent":"42%"},...
var ret = '';
$(arr).each(function () {
    var curr = this;
    //console.log(curr.id); 
    if(curr.id == stuffID){
        //console.log('>>found: ' + curr.percent);
        ret = curr.percent;
        //if found -> break loop
        return false; 
    }
});

@LiverpoolOwen approach is clean and nice, and if you want to use it combining with the object approach do this:

arr.find(function (value) {
if(value.id == stuffID)
   return value;  
}).percent;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.