Home > Mobile >  Retrieve all values from json array that match a variable value
Retrieve all values from json array that match a variable value

Time:10-17

I have a html select element with options(categories). Upon selecting an option(category) I get the option's value and store it in a variable.

const currentSelectValue = $('option:selected', this).attr('value');

I also have a JSON array with all subcategories.

const myObjArr = {
            data: [
                { id: 1, name: 'name_1', parent_id: '1' },
                { id: 2, name: 'name_2', parent_id: '2' },
                { id: 1, name: 'name_2', parent_id: '3' }
            ]
        };

My goal is to get the selected option value and match it to the list of subcategories, find the parent_id(which is the value from the selected option) and list all the results.

I'm new to JavaScript, so a detailed answer with an example would be much, much appreciated. Thanks in advance!

CodePudding user response:

Check this out JS .filter()

Assume you have 3 in your parent_id. Here is one line clean code solution

const myObjArr = {
  data: [{
      id: 1,
      name: 'name_1',
      parent_id: '1'
    },
    {
      id: 2,
      name: 'name_2',
      parent_id: '2'
    },
    {
      id: 1,
      name: 'name_2',
      parent_id: '3'
    }
  ]
};

// if parent id is 3
const currentSelectValue = 3

const selected = myObjArr.data.filter((ele,index) => ele.parent_id == currentSelectValue
)
console.log(selected)

  • Related