Get pairs of values ​​from the object below using javascript

I am learning javascript and this may be the main question, please help me understand below.

I create an array inside obejct as shown below to use the data later. Now I have to send the category as "Help" and should dynamically receive all its subcategories.

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

Thanks in advance

+4
source share
2 answers

You can filter first Array#filter, and then get the values ​​with 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; }
Run codeHide result

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; }
Run codeHide result
+3
source

To achieve this, you must use the method 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; }
Hide result
+2

Source: https://habr.com/ru/post/1675148/


All Articles