Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  107] [ 1]  / answers: 1 / hits: 18252  / 8 Years ago, fri, december 16, 2016, 12:00:00

I am unable to iterate the following JSON as I am expecting. The code is given as below :



$(document).ready(function() {
var data = '{employees:n
[{908887 : {firstName:John, lastName:Doe}},n
{98764 : {firstName:Anna, lastName:Smith}},n
{ 98762 : {firstName:Peter, lastName:Jones}}]}';

var empObj = JSON.parse(data);
for(var key in empObj.employees){
alert('key - ' + key + ' value - ' + empObj.employees[key]);
}
});


In alert, I am getting the keys 0, 1, 2, but I want: 908887, 98764, 98762. I also want to iterate over the values.



Please tell how to solve the issue.


More From » json

 Answers
36

This should do it:



var data = '{employees:n
[{908887 : {firstName:John, lastName:Doe}},n
{98764 : {firstName:Anna, lastName:Smith}},n
{ 98762 : {firstName:Peter, lastName:Jones}}]}';


var empObj = JSON.parse(data);

empObj.employees.forEach((item) => {
Object.entries(item).forEach(([key, val]) => {
console.log(`key-${key}-val-${JSON.stringify(val)}`)
});
});

[#59685] Tuesday, December 13, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neildrews

Total Points: 166
Total Questions: 103
Total Answers: 85

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
neildrews questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Tue, Oct 12, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
;