如何从对象获取数组

How to get an array from an object

本文关键字:获取 数组 对象      更新时间:2023-09-26
{
    "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 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"]]

试试这个

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

小提琴

试试

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

演示