0

Hi I am creating dynamic filter like this

Filter 1 --property 1 --property 2 --property 3

Filter 2 --property 1 --property 2 --property 3

Thats the code

    var js_filter = {};
    var creators_cat = [];

    $('.filter-item input').on('change',function (e) {
        var filter_type = $(this).attr('name');
        var filter_term = $(this).val();
        creators_cat.push( filter_term );
        js_filter["'"+filter_type+"'"] = creators_cat;
        console.log(js_filter);
    })

and that's a response I get

{'filter-product_cat[]': Array(4), 'filter-brands': Array(4)}
'filter-brands': (4) ['32', '29', '23', '36']
'filter-product_cat[]': (4) ['32', '29', '23', '36']
[[Prototype]]: Object

as you can see array keys are dynamically added but values are the same for both of the keys.

An I need to add these separately. Been looking for answer for quiet some time and didn't find something similar.

Would appreciate any help.

4
  • Why are you adding explicit quotes around filter_type? Commented Sep 30, 2021 at 22:03
  • There's only one creators_cat array, it's the value of both properties. Commented Sep 30, 2021 at 22:04
  • If you want to make a copy of the array for each property, use [...creators_cat] Commented Sep 30, 2021 at 22:05
  • The goal is to create it dynamically Add values by key like so filter-brands: (5) ['29', '23', '22'] filter-product_cat[]: (5) [ '36', '37' ] so instead of creators_cat there should be dynamic array. Like in PHP I could add $var[$key] = $value Commented Sep 30, 2021 at 22:19

1 Answer 1

1

You shouldn't be pushing onto a global array. Each filter input should have its own array of values.

Check if there's already an element of the js_filter object for the current filter_type. If not, create it as an empty array. Then push the current value onto the array.

$('.filter-item input').on('change', function(e) {
  var filter_type = $(this).attr('name');
  var filter_term = $(this).val();
  if (!js_filter[filter_type]) {
    js_filter[filter_type] = [];
  }
  js_filter[filter_type].push(filter_term);
  console.log(js_filter);
})
Sign up to request clarification or add additional context in comments.

3 Comments

Cannot read properties of undefined (reading 'push')
Sorry, left out ! in the test.
well that works ! Thank you!

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.