Loop through and extract item values from JSON notation using Javascript -
i have following json:
{"items": [ {"id":"5054","nodeid":"3286"}, {"id":"8888","nodeid":"7777"}, {"id":"3421","nodeid":"1234"}, {"id":"8748","nodeid":"2435"} ] }
when click button on page want run script retreives value of cookie stored json notation , loops through items within notation , compares id of button clicked ids stored in json. if id matches, nothing done. if not new item should added json object , saved cookie next time server loads page, different content displayed.
the addition of new item existing json notation easy bit , have code that. problem is, code looping through json notation doesn't seem working:
var cookietest = getcookie("wishlist"); /* json */ // check cookie exists if (cookietest != null) { var test = json.parse(cookietest) (prop in test) { console.log(prop); console.log(prop[0].id); } }
the first console.log seems return items when try , return id of first item in array, undefined returned.
what doing wrong here? appreciated.
you need first drill down "items" before can loop through array.
var cookietest = '{"items":[{"id":"5054","nodeid":"3286"},{"id":"8888","nodeid":"7777"},{"id":"3421","nodeid":"1234"},{"id":"8748","nodeid":"2435"}]}'; // check 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); } }
Comments
Post a Comment