如何从对象中获取数组

时间:2014-12-04 09:40:56

标签: javascript jquery

{
    "nextPointer": 7,
    "tagName": "tech",
    "newsList": [{
        "newsID": 43,
        "title": "This is a title",
        "description": "This is a demo description",
        "tagList": ["tech", "google", "all"]
    }, {
        "newsID": 42,
        "title": "This is a title no 2",
        "description": "This is a demo description no 2",
        "tagList": ["tech", "all"]
    }]
}

如何获取我的tagList数据,这是一个数组。

3 个答案:

答案 0 :(得分:0)

var data = {
    "nextPointer": 7,
        "tagName": "tech",
        "newsList": [{
        "newsID": 43,
            "title": "This is a title",
            "description": "This is a demo description",
            "tagList": ["tech", "google", "all"]
    }, {
        "newsID": 42,
            "title": "This is a title no 2",
            "description": "This is a demo description no 2",
            "tagList": ["tech", "all"]
    }]
}

var allTagList = [];
for (var i in data.newsList) {
    allTagList.push(data.newsList[i].tagList);
}

<强> DEMO

答案 1 :(得分:0)

假设此对象已分配变量:

    var jsonObj = {
        "nextPointer": 7,
            "tagName": "tech",
            "newsList": 
        [{
            "newsID": 43,
                "title": "This is a title",
                "description": "This is a demo description",
                "tagList": ["tech", "google", "all"]
        }, {
            "newsID": 42,
                "title": "This is a title no 2",
                "description": "This is a demo description no 2",
                "tagList": ["tech", "all"]
        }]
};

    var tagList = [];
    for(var i=0; i<json.newsList.length; i++) {
       tagList.push(json[i].tagList);
    }

这里有一个看起来像这样的数组:

[["tech", "google", "all"],["tech", "all"]]

答案 2 :(得分:0)

试试这个

var data = {
    "nextPointer": 7,
        "tagName": "tech",
        "newsList": [{
        "newsID": 43,
            "title": "This is a title",
            "description": "This is a demo description",
            "tagList": ["tech", "google", "all"]
    }, {
        "newsID": 42,
            "title": "This is a title no 2",
            "description": "This is a demo description no 2",
            "tagList": ["tech", "all"]
    }]
}


using jquery

var res = $.map(data.newsList, function(v ,i) { 
       return v.tagList;
});

using plain javascript

   var res = new Array();

  for(var i=0; i<data.newsList.length; i++) {
     res[i] = data[i].tagList;
   }


console.log(res);

Fiddle