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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With