0

Good Day!

How do I get values on my json via dot(.) syntax??

here is my json data:

[
{"productName":"31","description":"this is a red item","quantity":"","price":"15"},
{"productName":"35","description":"this color is blue","quantity":"","price":"600"}]

I tried using

var temp = $.cookie('Table_Rows'); <-- which contains the json data above;

for (var key in temp ) {
if (temp.hasOwnProperty(key)) {
  var obj = temp[key];
  for (var prop in obj) {
     if (obj.hasOwnProperty(prop)) {
        console.log(prop + " = " + obj[prop]);
     }
   }
  }
}

then I got this log on my console:

0 = [
0 = {
0 = "
0 = p
0 = r
0 = o
0 = d
0 = u
0 = c
0 = t
0 = N
0 = a
and so on..

Can you please help me comeup with a correct method please.. I want to access it like temp.productName. I know that this must be an easy fix, but its really confusing me right now. Thank you and have a nice day!

melvnberd
  • 3,093
  • 6
  • 32
  • 69

2 Answers2

1

Your array contains product items which you can access using a simple array index accessor.

But first, parse your cookie string object to JSON:

var jsonArray = JSON.parse(temp);

And then you should came up with:

var jsonArray = [{
    productName: "31",
    description: "this is a red item",
    quantity: "",
    price: "15"
}, {
    productName: "35",
    description: "this color is blue",
    quantity: "",
    price: "600"
}];

Which you can iterate like this:

for (obj in jsonArray) {
    console.log(jsonArray[obj].productName);
}

And get the following output:

31
35 

See my JSFiddle example for full code version.

Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
  • thank you @Yair Nevet for your answer! it worked perfectly! By the way in first its not working, then I realized I need to parse my data first! saves my day! – melvnberd Feb 10 '14 at 15:57
  • 1
    @melvnberd Yes, I know, see my update. Happy to help you. – Yair Nevet Feb 10 '14 at 15:59
1

You need to turn the JSON you get from the cookie value into a JavaScript object using JSON.parse

Then you can access the productName using an array method that is available in ES5

temp.forEach(function(item){ console.log(item.productName) });
ppoliani
  • 4,792
  • 3
  • 34
  • 62