Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get values in pairs from json array

Firstly, this is my json value i am getting from a php source:

[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]

After that, I want to get and oid value along with the corresponding cid value for example, oid=2 and cid=107 at one go, oid=4 and cid=98 at another and so on. I am trying to use jquery, ajax for this.

I have tried many answers for this, like: Javascript: Getting all existing keys in a JSON array and loop and get key/value pair for JSON array using jQuery but they don't solve my problem.

I tried this:

for (var i = 0; i < L; i++) { var obj = res[i]; for (var j in obj) { alert(j); }

but all this did was to return the key name, which again did not work on being used.

like image 278
xprilion Avatar asked Dec 26 '22 23:12

xprilion


1 Answers

So, you have an array of key/value pairs. Loop the array, at each index, log each pair:

var obj = [{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}];

for (var i = 0; i < obj.length; i++) {
    console.log("PAIR " + i + ": " + obj[i].oid);
    console.log("PAIR " + i + ": " + obj[i].cid);
}

Demo: http://jsfiddle.net/sTSX2/

like image 163
tymeJV Avatar answered Dec 28 '22 11:12

tymeJV