2017-04-19 68 views
4

我正在學習JavaScript,這可能是一個基本問題,請幫助我在下面獲得成果。使用javascript從以下對象獲取Key值對

我正在像下面這樣在obejct中構造一個數組以便稍後使用數據。現在,我必須將類別作爲「幫助」發送,並且需要動態獲取所有子類別的值。

[ 
    {"category":"Help","subcategory":"Email"}, 
    {"category":"Help","subcategory":"application"}, 
    {"category":"Help","subcategory":"Software"}, 
    {"category":"Help","subcategory":"Hardware"}, 
    {"category":"Request","subcategory":"Access"}, 
    {"category":"Request","subcategory":"Remote"}, 
    ] 

在此先感謝

回答

3

你可以用Array#filter先過濾,然後用Array#map得到的值。

var array = [{ category: "Help", subcategory: "Email" }, { category: "Help", subcategory: "application" }, { category: "Help", subcategory: "Software" }, { category: "Help", subcategory: "Hardware" }, { category: "Request", subcategory: "Access" }, { category: "Request", subcategory: "Remote" }], 
 
    subcategory = array 
 
     .filter(a => a.category === 'Help') 
 
     .map(a => a.subcategory); 
 
    
 
console.log(subcategory);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES5

var array = [{ category: "Help", subcategory: "Email" }, { category: "Help", subcategory: "application" }, { category: "Help", subcategory: "Software" }, { category: "Help", subcategory: "Hardware" }, { category: "Request", subcategory: "Access" }, { category: "Request", subcategory: "Remote" }], 
 
    subcategory = array 
 
     .filter(function (a) { return a.category === 'Help'; }) 
 
     .map(function (a) { return a.subcategory; }); 
 
    
 
console.log(subcategory);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

謝謝你,它的工作! –

2

您應該使用filter方法,以實現這一目標。

此外,使用map方法爲了創建一個新的數組只與subcategories

var array=[ 
 
    {"category":"Help","subcategory":"Email"}, 
 
    {"category":"Help","subcategory":"application"}, 
 
    {"category":"Help","subcategory":"Software"}, 
 
    {"category":"Help","subcategory":"Hardware"}, 
 
    {"category":"Request","subcategory":"Access"}, 
 
    {"category":"Request","subcategory":"Remote"}, 
 
]; 
 

 
var subcategories = array.filter(a => a.category === "Help").map(a => a.subcategory); 
 
console.log(subcategories);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

Hi Mihai,謝謝!當我嘗試在瀏覽器控制檯中運行上述腳本時,出現錯誤「Uncaught SyntaxError:Unexpected token =>」。如果你能詳細說明我的步驟,我會非常感謝 –

+0

我正在使用google chrome –

+0

可能不接受箭頭功能。 –