raj man raj man - 5 months ago 11
JSON Question

counting the number of json array index's

In my javascript ,i have a json like this,

var text = '{"employees":['+
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }' +
']}';


i used the below code to to parse my json.
obj1 = JSON.parse(text);


what i want to do is to store the json array elements with in a js array(var chartData1=[];). i used the below loop for storing the json array in chartData[]. i was able to successfully store the json array within chartData[] by giving the array condition as i<2.

here is my For loop,

for( i=0; i<=2; i++)
{
chartData1.push( [ obj1.employees[i]['firstName'], obj1.employees[i]['lastName'] ])
}


what i would like to do is to take of that '2' from the conditional statement with in the for loop and replace it with a variable or expression. i searched in many threads i found that i can use
obj1.employees.length;
(Somthing like this) but this doesnt work in my case . As i am completely a newbie in js i would like to recieve some help from experts. i am sorry for my english.Feel free to point me if i am going wrong somewhere.
thanks in advance.

Answer

obj1.employees.length should be fine as upper bound. I suspect you used the wrong comparison operator ( <= instead of <). See it working:

var obj1 = { "employees": [
  { "firstName": "John", "lastName": "Doe" }, 
  { "firstName": "Anna", "lastName": "Smith" },
  { "firstName":"Peter","lastName":"Jones" }
]};

var chartData1 = [];
for( i=0; i < obj1.employees.length; i++)
{ 
  chartData1.push( [ obj1.employees[i]['firstName'], obj1.employees[i]['lastName'] ])
}

console.log(JSON.stringify(chartData1));

However, there is a better and shorter solution, utilizing the Array.prototype.map function:

var obj1 = { "employees": [
  { "firstName": "John", "lastName": "Doe" }, 
  { "firstName": "Anna", "lastName": "Smith" },
  { "firstName":"Peter","lastName":"Jones" }
]};

var chartData1 = obj1.employees.map(e => [e.firstName, e.lastName]);

console.log(JSON.stringify(chartData1));

Comments