Javascript JSON Loop not counting more than 1 entry - javascript

I am reading some json code and at the end added a log that would give me the id.
My problem is that although there are 2 entries the log is only counting 1 and stops there.
var json = [{"main":[{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "hello1#email.se"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2#email.se"
}]}];
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj['main'][i].id);
}
Why is it only counting the 1 and not the 2 ?

A few of the answers here are going to confuse the hell out of you! They're missing the fact that you have an array within an object within an array.
json is an array, with 1 element
that object has a property main which itself is an array
it is this "3rd level" array which you are trying to loop through
var json = [{"main":[{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "hello1#email.se"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2#email.se"
}]}];
for(var i = 0; i < json[0].main.length; i++) {
var obj = json[0].main[i];
console.log(obj.id);
}

This happens because your array contains one object. I guess you need to access the main property:
for(var i = 0; i < json[0].main.length; i++) {
console.log(json[0].main[i].id);
}
var json = [{"main":[{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "hello1#email.se"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2#email.se"
}]}];
for(var i = 0; i < json[0].main.length; i++) {
console.log(json[0].main[i].id);
}

json is an array of object. So json[0] will return the main object
Use forEach to loop through the array
var _getMain = json[0].main // will return main array;
_getMain.forEach(function(item){
document.write('<pre>'+item.id+'</pre>')
})
JSFIDDLE

You have an array with 1 element ( 'main' ) and in the 'main' you have an array with 2 elements
Change to this:
for(var i = 0; i < json[0].length; i++) {
console.log(json[0][i].id);
}

Because you have to loop through json[0].main, not through json...

Related

Inserting an object inside an array fails

I have this data i have pulled from mongodb
{
"_id" : "RLvWTcsrbRXJeTqdB",
"examschoolid" : "5FF2JRddZdtTHuwkx",
"examsubjects" : [
{
"subject" : "Z4eLrwGwqG4pw4HKX"
},
{
"subject" : "fFcWby8ArpboizcT9"
}
],
"examay" : "NrsP4srFGfkc5cJkz",
"examterm" : "5A5dNTgAkdRr5j53j",
"examclass" : "gYF2wE4wBCRy9a3ZC",
"examname" : "First",
"examdate" : ISODate("2016-05-07T22:41:00Z"),
"examresultsstatus" : "notreleased"
}
I want to iterate examsubjects and finally insert an object inside my array and get an array like this
"examsubjects" : [
{
"Z4eLrwGwqG4pw4HKX" : "0",
"fFcWby8ArpboizcT9" : "0"
}
],
This is my code
var result = new Array();
for (i = 0; i < doc.examsubjects.length; i++) {
var arr = {};
for (var prop in doc.examsubjects[i]) {
arr[doc.examsubjects[i][prop]] = 0;
}
result.push(arr);
}
which gives me this array
"examsubjects" : [
{
"Z4eLrwGwqG4pw4HKX" : 0
},
{
"fFcWby8ArpboizcT9" : 0
}
],
How can i get the array i want?.
In your attempt, you initialize an empty array and push a new object into it for every object in your examsubjects array, when what you want to do is put the data from all your exam subjects into just one object, when you then apparently want to be in an array. One of the many ways to accomplish that is like this:
var result = [{}];
for (i = 0; i < doc.examsubjects.length; i++) {
for (var prop in doc.examsubjects[i]) {
// Here we repeatedly modify the single
// object in our results array
result[0][doc.examsubjects[i][prop]] = 0;
}
}
// result now looks like [{"Z4eLrwGwqG4pw4HKX": "0", "fFcWby8ArpboizcT9": 0"}]

AngularJS Json Array

I have the following JSON:
{
"_id" : ObjectId("542e65368a1cec1227ae2bac"),
"result" : {
"full" : {
"Array1" : [
"mytext1",
"mytext2"
],
"Array2" : [
"mytext3",
"mytext3"
]
}
}
}
To get everything: OK
console.log("response ", response);
To get the _id: OK
console.log("_id ", response._id);
But I can't access to mytext1, mytext2, ...
How I can proceed with angularjs?
Thanks for your help !
response is an object. result is an object. full is an object. Array1 and Array2 are, obviously enough, arrays.
For mytext1:
response.result.full.Array1[0]
For mytext2:
response.result.full.Array1[1]
For mytext3:
response.result.full.Array2[0]
For mytext4:
response.result.full.Array2[1]
If you want to log everything in the array, use a simple for...loop:
var arr = response.result.full.Array1;
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i]);
}
var q = {
"_id" : "542e65368a1cec1227ae2bac",
"result" : {
"full" : {
"Array1" : [
"mytext1",
"mytext2"
],
"Array2" : [
"mytext3",
"mytext3"
]
}
}
};
//The next for iterates over the names Array1, Array2 (and if you have more)
for(var array in q.result.full)
{
//This for iterates over the elements of each array
for(i = 0; i < q.result.full[array].length; i++)
{
console.log(q.result.full[array][i]);
}
}

Get index of array of objects via jquery

I have the following array:
var = array[
{"id" : "aa", "description" : "some description"},
{"id" : "bb", "description" : "some more description"},
{"id" : "cc", "description" : "a lot of description"}]
and I try to find the index of the array that contains the id === "bb". The solution I came up with is the following:
var i = 0;
while(array[i].id != "bb"){
i++;
}
alert(i) //returns 1
Is there an easier way that has cross-browser functionality? I tried $.inArray(id,array) but it doesn't work.
I don't see any problem with the complexity of your code, but I would recommend a couple of changes including adding some validation in case the value does not exists. Further more you can wrap it all in a reusable helper function...
function getArrayIndexForKey(arr, key, val){
for(var i = 0; i < arr.length; i++){
if(arr[i][key] == val)
return i;
}
return -1;
}
This can then be used in your example like so:
var index = getArrayIndexForKey(array, "id", "bb");
//index will be -1 if the "bb" is not found
Here is a working example
NOTE: This should be cross browser compatible, and will also likely be faster than any JQuery alternative.
var myArray = [your array];
var i = 0;
$.each(myArray, function(){
if (this.id === 'bb') return false;
i++;
})
console.log(i) // will log '1'
Update with modern JS.
let index
myArray.map(function(item, i){
if (item.id === 'cc') index = i
})
console.log(index) // will log '2'
inArray can't work with multidimensional array so try like the following
var globalarray= [
{"id" : "aa", "description" : "some description1"},
{"id" : "bb", "description" : "some more description"},
{"id" : "cc", "description" : "a lot of description"}];
var theIndex = -1;
for (var i = 0; i < globalarray.length; i++) {
if (globalarray[i].id == 'bb') {
theIndex = i;
break;
}
}
alert(theIndex);
Demo
You can use jQuery.each - http://api.jquery.com/jQuery.each/
var i;
jQuery.each(array, function(index, value){
if(value.id == 'bb'){
i = index;
return false; // retrun false to stop the loops
}
});
Object.keys(yourObject).indexOf(yourValue);

JSON count an Array elements and wrap in

Well I've just discovered JSON today but I have a problem using it correctly. I really can't find a solution...
Basically, I just want to count the elements of my array (count all the dM), and wrap on a specific element (dM1 for example).
Here is my code so that you can understand: http://jsfiddle.net/dRycS/9/
Adding to what #Pointy said here is your code modified:
JSFiddle Demo
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var dMContent = {
"dM1" : [
{
"name" : "EeEeEeEe",
"link" : "http://test.com"
},
{
"name" : "FfFfFfFf",
"link" : "http://test.com"
},
{
"name" : "GgGgGgGg",
"link" : "http://test.com"
}
],
"dM2" : [
{
"name" : "EeEeEeEe",
"link" : "http://test.com"
},
{
"name" : "FfFfFfFf",
"link" : "http://test.com"
}
],
"dM3" : [
{
"name" : "EeEeEeEe",
"link" : "http://test.com"
}
]
};
var STORAGE = JSON.stringify(dMContent);
var parsed = JSON.parse(STORAGE);
// WHAT I WANT TO DO
// Count the number of dM
console.log(Object.size(parsed)); //gives you 3
//display the content
for(var i in parsed){
console.log('data in ' + i);
for(var j=0; j<parsed[i].length; j++){
console.log(parsed[i][j].name + ' ' + parsed[i][j].link);
}
}
What you've got there is not an Array; it's an Object. Array objects do have a "length" property, but Objects do not.
It's not clear exactly what you want; if you wanted to count every property of every object inside of "dMContent", you'd write something to count recursively. For a single "layer" of an object, something like this might be what you want:
function objectSize(obj) {
var count = 0;
for (var k in obj) {
if (obj.hasOwnProperty(k)) ++count;
}
return count;
}
In your code dMContent is an Object, not an Array.
To count elements in an Object, do this:
var i = 0;
for (x in parsed) {
if (parsed.hasOwnProperty(x)) {
i++;
}
}
alert(i);
Try this:
function objectCount(obj) {
objectcount = 0;
$.each(obj, function(index, item) {
objectcount = objectcount + item.length;
});
return objectcount;
}
objectCount(obj);
where obj is a json object with json array as sub objects

JavaScript function, which reads connections between objects

I have a JavaScript literal:
var members = {
"mother": {
"name" : "Mary",
"age" : "48",
"connection": {
"brother" : "sun"
}
},
"father": {
"name" : "Bill",
"age" : "50"
},
"brother": {
"name" : "Alex",
"age" : "28"
}
}
Than I have a function, which should read connections from the literal above. It looks like this:
function findRelations(members){
var wires = new Array();
var count = 0;
for (n = 0; n < members.length; n++){
alert(members.length); // this alert is undefined
if (members[n].connection){
for (i = 0; i < members[n].connection[0].length; i++){
var mw = new Array();
var destination = 0;
for (m = 0; m < members.length; m ++){
if (members[m] == members[n].connection[0]){
destination = m;
mw = [n, destination];
wires [count] = mw;
count++;
}
}
}
}
}
return wires;
}
However, when I run this function, I get nothing. And the first alert, which is placed inside the function shows 'undefined' at all.
findRelations(members);
alert("Found " + wires.length + " connections");
I guess that's because of JavaScript literal. Could you suggest how to change a function or perhaps to change litteral to JSON array to get it work?! And at the end to get 'm' and 'n' values as numbers.
What is a 'literal'? I guess you mean 'an object created using the literal notation'.
Only Array's (and strings) have a length property, what you want is to loop through the properties
for (var prop in members) {
if (members.hasOwnProperty(prop)) {
alert("members has property " + prop);
}
}
This should get you on the right path as its not easy to follow the rest of the logic
The alert gives you "undefined" because your function seems to be expecting an array whereas your "members" variable is an Object.
the "length" property is not defined on an object. So,
var a = {
name:'test',
age:56
};
console.log(a.length); //undefined
The same is the reason for getting no response as well.

Categories