Iterating data to get value - javascript

I have following loop
for (var i in data) {
console.log(data[i])
}
Data that I for loop is iterating through is
"data": [
{
"MainArea": "North West"
},
{
"MainArea": "South West"
},
When I run it I get following output in firebug
[Object { MainArea="North West"},
Object { MainArea="South West"}]
What I am trying to get is just the value of it. So that when I tried
console.log(data[i].MainArea)
Hoping to get just the "North West" and South West" values, instead
I get "undefined" in my console.

Try following:
console.log(data[i].MainArea);
You are trying to get information out of objects property. Since your variables enclosed to json format list you can reach your variables through named properties.
UPDATE: According your addition to the your original question I created DEMO.
var myObj = {"data": [
{
"MainArea": "North West"
},
{
"MainArea": "South West"
},
],
},
data = myObj['data'],
data_length=data.length;
for (var i= 0; i < data_length; i++)
{
console.log(data[i].MainArea);
}
Keep in mind that when you are iterating key value pairs you should use for ... in loop while when you are iterating through array you should use for loop. For example if your data property contains sorted array, for ... in loop will not guaranty to loop from array item 0 to N. It means it will not follow sequence. So use only for loops for array and for ... in for non-array objects. Read about this in here. Some jsPerf comparison be seen here.

The problem is the data object you are iterating has another property called data which is an array containing the target objects, and of course the property key you need to use is MainArea so try
var data = {
"data": [{
"MainArea": "North West"
}, {
"MainArea": "South West"
}]
}
for (var i in data.data) {
console.log(data.data[i].MainArea)
}
Demo: Fiddle

The object is defined as this:
{ MainArea="North West" }
So it has only one property, called MainArea. There's no property called value so of course value is undefined. Try:
console.log(data[i].MainArea)

Related

How to acces to the data from several json objects inside an array position

I'm making a little app in nodejs, I'm struggling trying to print some data provenient from a json which has the following structure:
{
"courses": [
{
"java": [
{ "attendees": 43 },
{ "subject": "Crash course" }
]
},
{
"python":
{
"occurrences": [
{ "attendees": 24 },
{ "subject": "another crash course" },
{ "notes": "completed with issues" }
,
{ "attendees": 30 },
{ "subject": "another crash course" },
{ "notes": "completed with issues" }
]
}
}
],
}
If I want to print the attendees at 'java' I do:
console.log(myJSON.courses[0]['java'][0]['attendees']);
which prints
43
and if I want to print the notes of the 2nd occurrence of the python course I do:
console.log(myJSON.courses[1]['python']['occurrences'][2]['notes']);
which prints:
completed with issues
The before mentioned cases are correct, but what I want to do is to print the keys of 'java' ('attendees' and 'subject'), as you can see Java is an array and in its unique position it has two json objects, I've tried with:
console.log(myJSON.courses[0]['java'][0].keys;
and with
console.log(myJSON.courses[0]['java'].keys;
but they print "undefined" and "[Function: keys]" respectively.
What I'm missing here?
Could anybody help me please?:(
myJSON.courses[0]['java'] is an array with indexes. Where each index holds an object with keys. Your array doesn't exactly have the keys you want (the keys of an array are its indexes: 0, 1 etc...)
Instead, you want to access all the keys from the objects in the myJSON.courses[0]['java'] array.
You can do this by using .map and Object.keys. .map will allow you to get and convert every object in your myJSON.courses[0]['java'] array. Object.keys() will allow you to get an array of keys from the given object (in your case your array will be of length 1, and so you can access index 0 of this array).
const myJSON = {courses:[{java:[{attendees:43},{subject:"Crash course"}]},{python:{occurrences:[{attendees:24},{subject:"another crash course"},{notes:"completed with issues"},{attendees:30},{subject:"another crash course"},{notes:"completed with issues"}]}}]};
const myKeys = myJSON.courses[0]['java'].map(obj => Object.keys(obj)[0]);
console.log(myKeys);
If you have multiple keys in your objects within an array, you can also use .flatMap (take note of browser support):
const myJSON = {courses:[{java:[{attendees:43},{subject:"Crash course"}]},{python:{occurrences:[{attendees:24},{subject:"another crash course"},{notes:"completed with issues"},{attendees:30},{subject:"another crash course"},{notes:"completed with issues"}]}}]};
const myKeys = myJSON.courses[0]['java'].flatMap(Object.keys);
console.log(myKeys);

Year as an index

I had this dictionary
"name" : {
"2016" : {
"1" : "info"
}
}
I added it to sessionStorage using json.stringfy and it worked perfectly. I then appended another dictionary to the first one:
name: {
2016: {
1: {
info: {
0: {
"question": "qs1",
"information": "info1"
},
1: {
"question": "qs12",
"information": "info2"
},
}
}
}
}
and I did the same convert to a string using json.stringfy. Then I noticed this:
name: {
0 : "2016",
1 : null,
2 : null, //until 2016
2016: {
1: {
info: {
0: {
"question": "qs1",
"information": "info1"
},
1: {
"question": "qs12",
"information": "info2"
},
}
}
}
I don't know why it's counting when the typeof tells me that it's a string, not a number. Also, I don't understand why it didn't do this with the first dictionary.
Here is the code:
(function($){
x = {
"info": {
"0": {
"question": "qs1",
"information": "info1"
},
"1": {
"question": "qs12",
"information": "info2"
},
}
}
var sesion = {};
var stringinfo;
sesion["name"]=["2016"];
sesion["name"]["2016"]=["1"];
sesion["name"]["2016"]["1"] = x;
stringinfo = json.stringfy(sesion);
console.log(sesion);
console.log(stringinfo)
}(jQuery))
Try it and tell me if using a number(string) as an index does that! How can I resolve this? Thank you.
you are confusing arrays ([]) and objects ({}). At the beginning you say:
I got this array:
"name" : {
"2016" : {
"1" : "info"
}
But this is an object.
Your question is a bit difficult to follow. But if you instantiate an empty array, and tell it that numer 2016 should have a certain value, it will fill up the rest with empty (null) values.
You want to use an object, rather than an array.
Look at your code where objects and arrays get mixed up. You want to be using an object, with the key "2016", not an array which uses numbers as indexes.
added information after reviewing supplied code
(btw I fixed spelling of 'sesion' to 'session' in explanation below)
the line:
var session = {}
makes an empty object. The line:
session["name"]=["2016"];
sets the property "name" of this object to be an array containing the only string "2016".
Now it gets interesting; you just made the name property an array, so the line
session["name"]["2016"]=["1"];
makes the compiler use the following logic; since session["name"] is an array, you probably don't mean to set a property on it when you refer to session["name"]["2016"]; the string "2016" gets coerced to a number and it puts a new array on it, containing the string "1".
At this point I must point out that your code is not running, and after fixing it the output is not like you put it in your question. What happens after is the same as before, just you put in the new array at the 1st spot your object in x.
The main problem in your code as stated before sits in mixing arrays and objects.
replace the line
session["name"]=["2016"];
for example with:
session["name"] = {}
to instantiate an object on which you can put properties such as "2016", and I am not sure what the exact objective is, but if you want to make an array under this property, do it something like:
session["name"]["2016"]=[x];

How to find JSON object contains Object or Array in Javascript?

I am working Angular js project, I am getting form server response is JSON Object. That JSON Object contains nested Objects and Arrays. for every time i need write lot coding getting the value of key
Ex:
{
"mapData": {
"data": [
{
"key": "name",
"value": "abc"
},
{
"key": "name",
"value": "bcd"
},
{
"key": "name",
"value": "vbc"
}
]
}
}
what i was tried example is so many times, it is not related above example.
for(var key in object) {
if(key=="Id"){
Id= object[key].fieldValue;
secondData.forEach(function(item){
for(var innerItem in item){
if(innerItem =="Id"){
if(Id==item[innerItem].fieldValue){
FinalData.push(item);
}
}
}
});
}
}
Is there any way generic way Instead of writing every time for for loop and For Each loop.
could you please suggest any things
Thanks in advance
mapData.data[i].key will return your key value. i is index of your data array you can easily iterate data by
for(var i =0;i<mapData.data.length;i++){}

How to parse through a JSON object Map

If I have a JSON Object Map :
var dataItem=[{
"Lucy":{
"id": 456,
"full_name": "GOOBER, ANGELA",
"user_id": "2733245678",
"stin": "2733212346"
},
"Myra":{
"id": 123,
"full_name": "BOB, STEVE",
"user_id": "abc213",
"stin": "9040923411"
}
}]
I want to iterate through this list and access the names (i.e. Lucy, Myra ) and corresponding information
All the loops that I came across looped through the list like this :
var dataItem = [
{"Name":"Nthal","Class":3,"SubjectName":"English "},
{"Name":"Mishal","Class":4,"SubjectName":"Grammer"},
{"Name":"Sanjeev","Class":3,"SubjectName":"Social"},
{"Name":"Michal","Class":5,"SubjectName":"Gk"},
]
for(x in dataItem)
{
alert(dataItem[x].Name);
alert(dataItem[x].Class);
alert(dataItem[x].SubjectName);
}
Thanks in advance
What you have there is not JSON, maybe because you've already parsed it. You have is an array consisting of a single object, with names for its keys. Regardless, I'll show you how to access that data:
var data = dataItem[0];
for(name in data) {
alert(name);
alert(data[name].id);
alert(data[name].full_name);
}
for (var x in dataItem[0]) {
if (dataItem[0].hasOwnProperty(x)) {
console.log(x);
}
}
http://jsfiddle.net/B44LW/
If you want other properties, then you can use the bracket notation:
dataItem[0][x].id

Parse JSON with jQuery

I am trying to parse the following JSON with jQuery and get each id value. Can anyone advise?
[
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
]
So far I have:
$.each(test, function(i,item){
alert(item);
});
But that simply lists every value. How can I
That'll list every object in your array, to get the id property of the one you're on, just add .id like this:
$.each(test, function(i,item){
alert(item.id);
});
If test is a string containing JSON, you can parse it with jQuery.parseJSON, which will return a JavaScript object.
If test is written like this:
var test = [
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
];
...it already is a JavaScript object; specifically an array. jQuery.each will loop through each array entry. If you want to loop through the properties of those entries as well, you can use a second loop:
$.each(test, function(outerKey, outerValue) {
// At this level, outerKey is the key (index, mostly) in the
// outer array, so 0 or 1 in your case. outerValue is the
// object assigned to that array entry.
$.each(outerValue, function(innerKey, innerValue) {
// At this level, innerKey is the property name in the object,
// and innerValue is the property's value
});
});
Live example

Categories