4

I am learning javascript and this may be a basic question, please help me to acheive below.

I am constructing an array inside obejct like below to use data later. Now, i have to send category as "Help" and need to get all it's subcategory values dynamically.

 [
    {"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

2 Answers 2

3

You could filter with Array#filter first 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; }

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

Sign up to request clarification or add additional context in comments.

Comments

2

You should use filter method in order to achieve this.

Also, use map method in order to create a new array only with the 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; }

1 Comment

Hi Mihai, Thank you !! when i try to run the above script in browser console i am getting below error "Uncaught SyntaxError: Unexpected token =>". I will be really greatful if you can give me the steps to do it in detail

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.