2014-12-04 41 views
-1
{ 
    "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數據是一個數組。如何從一個對象獲取數組

回答

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

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

相關問題