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"}]
Related
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...
I need to loop through array and each array in array that has extra values, push them to their parent array as separate item. I hope this makes sense..
This is the structure of my initial array:
{type:
[ 0:
value: "tomato"
],
[ 1:
{value: "apple",
[ extras:
[ 0: { value: "green" } ],
[ 1: { value: "red" } ]
]
],
[ 2:
value: "pineapple"
]
}
What the result would have to look like:
[type:
[ 0:
tomato
],
[ 1:
apple,
green,
red
],
[ 2:
pineapple
]
]
What I've tried and failed: (I also commented the error I get on right line)
var response = /* json of first codeblock in question is response from ajax */;
var items = JSON.parse( response );
var type = Object.keys( items )[0];
var myArray = []
var count = items[type].lenght;
//Loop through main items in "type"
for( i = 0; i < count; i++ ) {
var value = items[type][i][value];
myArray[type][i] = [value]; //Uncaught TypeError: Cannot set property '0' of undefined
if( items[type][i][extras] ) {
var extracount = items[type][i][extras].lenght;
//Loop through extras
for( k = 0; k < extracount; k++ ) {
var extra = items[type][i][extras][k][value];
myArray[type][i].push( extra );
}
}
}
My main problem that I don't understand and that seems to be the problem in my example as well:
If I declare an empty array, how do I:
push an item to that array also declaring a new array around that item?
push another item to that array that was made around the first item?
This is what I believe you want. The following code may be incorrect, because I'm approximating what I believe your items object contains.
var items = {
type: [
{
value: "tomato"
},
{
value: "apple",
extras: [
{
value: "green"
}, {
value: "red"
}
]
},
{
value: "pineapple"
}
]
};
var myArray = {
type: []
};
var count = items['type'].length;
//Loop through main items in "type"
for (i = 0; i < count; i++) {
var subarray = [];
subarray.push(items['type'][i]['value']);
if (items['type'][i]['extras']) {
var extracount = items['type'][i]['extras'].length;
//Loop through extras
for (k = 0; k < extracount; k++) {
var extra = items['type'][i]['extras'][k]['value'];
subarray.push(extra);
}
}
myArray['type'].push(subarray);
}
Some notes:
You will definitely need to learn the difference between an array and an object in javascript. There are plenty of resources online for this.
When retrieving/manipulating a property prop from an object obj (i.e. for a key-value pair), you will need to use obj.prop or obj['prop']. Note the use of a string in the latter example.
For an array arr, you should use arr.push(value) to push a new value onto the array.
Your problem is here:
var value = items[type][i][value];
you should change it to
var value = items[type][i].value;
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]);
}
}
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
Basically I have the following JSON-originated Object:
({
"id" : 3,
"clientName" : "Avia",
"monthlyactiveusers" : 2083,
"dailynewlikes" : 0,
"totallikes" : 4258,
"usersgraph" : {
"sTotalLikes" : [{
"likes" : 79,
"date" : "1/1/2010"
},
{
"likes" : 116,
"date" : "1/1/2010"
}],
"sDailyActiveUsers" : [{
"likes" : 79,
"date" : "1/1/2010"
},
{
"likes" : 116,
"date" : "1/1/2010"
}]
}
});
And I need the following result:
sTotalLikes = [['1/1/2010', 79],['1/1/2010', 79],['1/11/2010', 79]];
sDailyActiveUsers = [['1/1/2010', 10],['1/5/2010', 300],['1/11/2010', 220]];
I know you can iterate through the object to build the array using the following code but I couldn't figure out how to build the JavaScript array itself. Thanks in advance for help.
var sTotalLikes = new Array();
for (var i = 0; i < usersgraph.sTotalLikes.length; i++) {
//how do I build the arry ?
sTotalLikes[i]
}
You'll have to Iteration through each item in sTotalLikes and sDailyActiveUsers.
You can also see the live demo here for complete and working program with comments. :)
// declare arrays for storing total likes and active users
var totalLikes = [];
var activeUsers = [];
// first iterate for total likes
for (var i = 0; i < data.usersgraph.sTotalLikes.length; i ++)
{
var like = data.usersgraph.sTotalLikes[i];
// create a new array of date and likes
// and push into total likes
totalLikes.push([like.date, like.likes]);
}
// then iterate for active users
for (var i = 0; i < data.usersgraph.sDailyActiveUsers.length; i ++)
{
var user = data.usersgraph.sDailyActiveUsers[i];
// create a new array of date and likes
// and push into active users
activeUsers.push([user.date, user.likes]);
}
hope this helps!
Try this.. you can easily extend it for sDailyActiveUsers
var sTotalLikes = new Array();
var lsTotalLikes = usersgraph.sTotalLikes;
for (var i = 0; i < lsTotalLikes.length; i++)
{
var obj = lsTotalLikes[i];
var lArr = []
lArr.push(obj.date);
lArr.push(obj.likes);
sTotalLikes.push(lArr)
}
It looks to me like you just want to look at the values of the objects.
var usersgraph = { ... }; // pulled from the data in your question
var result = {};
for (users_key in usersgraph) {
var vals = [];
var data = usersgraph[users_key]
for (k in data) {
vals.push(values(data[k]));
// or if you need to order them differently..
//vals.push([ data[k]['date'], data[k]['likes'] ]);
}
result[users_key] = vals;
}
Oh, if you had not guessed already you can use [] to create an array and {} to create an object/associative array.
Like this (referring to your code):
/* inside your for loop */
sTotalLikes.push([
usersgraph.sTotalLikes[i].date,
usersgraph.sTotalLikes[i].likes
])