如何从json对象构建键值的JavaScript数组

时间:2010-12-18 01:41:28

标签: javascript jquery arrays json object

基本上我有以下由JSON发起的对象:

({
    "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"
        }]
    }
});

我需要以下结果:

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]];

我知道您可以使用以下代码遍历对象来构建数组,但我无法弄清楚如何构建JavaScript数组本身。在此先感谢您的帮助。

var sTotalLikes = new Array();

 for (var i = 0; i < usersgraph.sTotalLikes.length; i++) {
    //how do I build the arry ?
    sTotalLikes[i]
  }

4 个答案:

答案 0 :(得分:2)

试试这个..你可以轻松地为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) 
  }

答案 1 :(得分:2)

您需要对sTotalLikessDailyActiveUsers中的每个项目进行迭代。

您还可以see the live demo here获取有关评论的完整且有效的计划。 :)

// 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]);
}

希望这有帮助!

答案 2 :(得分:1)

在我看来,你只想看看对象的价值。

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;
}

哦,如果您还没有猜到,可以使用[]创建数组,{}创建对象/关联数组。

答案 3 :(得分:0)

像这样(指你的代码):

/* inside your for loop */
sTotalLikes.push([
    usersgraph.sTotalLikes[i].date,
    usersgraph.sTotalLikes[i].likes
])