How to add an array with dynamic values in an object with dynamic properties?

Asked

Viewed 150 times

0

How best to create and populate an array dynamically and insert it into a dynamic property of an object?

We can use the following scenario:

$(function() {

  const products = {};

  const items = $('.items .item');
  $(items).each(function(i) {
    /* As propriedades do objeto devem ser o data-type e cada propriedade
     * terá um array com os data-id
     */
  });
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="items">
  <span class="item" data-id="1" data-type="eletronics">Phone</span>
  <span class="item" data-id="1" data-type="sports">Ball</span>
  <span class="item" data-id="2" data-type="sports">Shoes</span>
  <span class="item" data-id="3" data-type="sports">T-Shirt</span>
  <span class="item" data-id="2" data-type="eletronics">TV</span>
</div>

The expected result would be this:

// console.log(products);

{
    eletronics: [1, 2],
    sports: [1, 2, 3]
}
  • Within your array the values eletronics, sports comes dynamically ?

  • Yes, they are dynamic.

1 answer

1


Based on what you’ve given me, I’ve made some changes and managed to replicate your result.

<script>
var products = {};

$(function() {

  const items = $('.items .item');
  $(items).each(function(i) {       
    let type = $(this).data("type");
    let id = $(this).data("id");
    if(products[type] == undefined){
            products[type] = [];
    }
    products[type].push(id);
  });

});

</script>
  • Thanks for the reply, it worked right!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.