Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Separate values from json array using jquery.?

This is my json

{
  "data": [
    [
      "1",
      "Skylar Melovia"
    ],
    [
      "4",
      "Mathew Johnson"
    ]
  ]
}

this is my code jquery Code

for(i=0; i<= contacts.data.length; i++) {
    $.each(contacts.data[i], function( index, objValue ){
        alert("id "+objValue);
    });
}

i got the data in my objValue but i want to store separately in array of id and name it looks like this look at my code is bellow

var id=[];
var name = [];
for(i=0; i<= contacts.data.length; i++){
    $.each(contacts.data[i], function( index, objValue ) {
        id.push(objValue[index]); // This will be the value "1" from above JSON
        name.push(objValue[index]); // This will be the value "Skylar Melovia"   from above JSON
    });
}

How can i do this.

like image 838
Aadi Avatar asked Oct 04 '22 01:10

Aadi


2 Answers

 $.each(contacts.data, function( index, objValue )
 {
    id.push(objValue[0]); // This will be the value "1" from above JSON
    name.push(objValue[1]); // This will be the value "Skylar Melovia"   from above JSON

 });

Edit, alternative usage :

 $.each(contacts.data, function()
 {
    id.push(this[0]); // This will be the value "1" from above JSON
    name.push(this[1]); // This will be the value "Skylar Melovia"   from above JSON
 });

The $.each will iterate over contacts.data which is :

[
    //index 1
    [
      "1",
      "Skylar Melovia"
    ],
    //index=2
    [
      "4",
      "Mathew Johnson"
    ]

]

The anomnymous function you give with signature function(index,Objvalue) will be applied on each element with index it's index in the contact.data array and objValue its value. For index=1 you will have :

objValue=[
          "1",
          "Skylar Melovia"
        ]

Then you can access objValue[0] and objValue[1].

EDIT (in response to Dutchie432 comment and answer ;) ): Faster way to do it without jQuery, $.each is nicer to write and read but here you use plain old JS :

for(i=0; i<contacts.data.length; i++){
    ids.push(contacts.data[i][0];
    name.push(contacts.data[i][1];
}
like image 59
TecHunter Avatar answered Oct 19 '22 12:10

TecHunter


Perhaps I am not understanding fully, but I think you are looping through the data items, and then looping through the contained values as well. I think what you want is just to loop through the data items and pull values 0 and 1 respectively.

Also, I believe you want the less than (<) operator in your loop as opposed to the less than or equal to (<=)

for(i=0; i<contacts.data.length; i++){
    ids.push(contacts.data[i][0];
    name.push(contacts.data[i][1];
}
like image 21
Dutchie432 Avatar answered Oct 19 '22 13:10

Dutchie432