简体   繁体   中英

Loop through and extract item values from JSON notation using Javascript

I have the following JSON:

{"items":
 [
  {"id":"5054","nodeId":"3286"},
  {"id":"8888","nodeId":"7777"},
  {"id":"3421","nodeId":"1234"},
  {"id":"8748","nodeId":"2435"}
 ]
}

When I click a button on my page I want to run a script that retreives the value of a cookie which is stored as JSON notation and then loops through the items within the notation and compares the id of the button that was clicked to the ids stored in the JSON. If the id matches, nothing is done. If it does not then the new item should be added to the JSON object and saved back to the cookie so the next time the server loads the page, different content is displayed.

The addition of a new item to the existing JSON notation is the easy bit and I already have the code for that. The problem is, my code for looping through the JSON notation doesn't seem to be working:

var cookieTest = getCookie("wishlist"); /* JSON */

    // Check a cookie exists
    if (cookieTest != null) {

        var test = JSON.parse(cookieTest)

        for (prop in test) {
            console.log(prop);
            console.log(prop[0].id);
        }
    }

The first console.log seems to return items however when I try and return the id of the first item in the array, undefined is returned.

What am I doing wrong here? Any help would be greatly appreciated.

The for (in) loop iterates over the property names of an object, not the property values .

var prop;
for (var p in test) {
  prop = test[p];
  console.log(p, prop, prop[0].id);
}

PS: Or if you just want to iterate over the property with name items of test (you already know the property name you're interested in and that the value will be an array).

for (var i = 0, e = test.items.length; i < e; ++i) {
  console.log(i, test.items[i], test.items[i].id);
}

You need to first drill down to "items" before you can loop through the array.

var cookieTest = '{"items":[{"id":"5054","nodeId":"3286"},{"id":"8888","nodeId":"7777"},{"id":"3421","nodeId":"1234"},{"id":"8748","nodeId":"2435"}]}';
// Check a cookie exists
    if (cookieTest != null) {

        var test = JSON.parse(cookieTest)
        var items = test.items ? test.items : [];
        for(thing in items) {
            var current = items[thing];
            console.log(current.id);
        }
    }

http://jsfiddle.net/6n8dr/

Try jQuery see if it works:

var obj = jQuery.parseJSON(cookieTest);
console.log(obj.items[0].id);

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