0

I have a JavaScript object {} with a bunch of values, one of the values is an array []. After converting to JSON will look something like this.

{
  "header-name": "",
  "header-role": "",
  "header-phone": "",
  "header-website": "",
  "header-email": "",
  "header-location": "",
  "exp-one": "ssfsdf",
  "exp-two": "sdfsdf",
  "exp-three": "",
  "exp-four": "",
  "exp-five": "",
  "exp-six": "",
  "exp-sub": [
    "1",
    "2",
    "3",
    "4",
    "5"
  ]
}

I am able to loop through the JSON using var result = $.parseJSON(data); $.each(result, function(k, v) {});

What i am trying to do is also loop over that array that sits in the object "exp-sub", something like.

$.each(result, function(k, v) {
    if (v == "exp-sub"){
        $.each(k, function(key, val) {
            //loop over array, this doesn't work though
        }
    }
});

Have tried with a for loop also but does not work either, any help will be appreciated thanks.

3
  • try if (k == "exp-sub") instead of if (v == "exp-sub") Commented Sep 2, 2018 at 16:06
  • oops, the question was already answered! never mind Commented Sep 2, 2018 at 16:07
  • Was a typo, i was doing K and not V, problem solved below, thanks Commented Sep 2, 2018 at 16:08

1 Answer 1

1

Actually k is key i.e.exp-sub so you have to compare k and iterate over v

var result={"header-name":"","header-role":"","header-phone":"","header-website":"","header-email":"","header-location":"","exp-one":"ssfsdf","exp-two":"sdfsdf","exp-three":"","exp-four":"","exp-five":"","exp-six":"","exp-sub":["1","2","3","4","5"]}

$.each(result, function(k, v) {
    //console.log(k, v)
    if (k == "exp-sub"){
      $.each(v, function(index, val) {
       console.log(val)
}); 
    }
});
<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.

1 Comment

Oh, loop the values of the array, not the key. Now i feel dumb, thank you.

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.