1

I have an array like this

products = [{id}, {id}, {id}, {id}]

I want to place available ids in a parent div

<div data-ids="{{ place ids here }}"> <!-- parent div -->
     products.forEach(function(e){
        <div class="product">
            console.log(e.id);
        </div>
     });
</div>

I would like to put all the available ids in the parent data-ids,

is there any way to put it without an additional loop specifically for placing ids in parent div?

huaLin
  • 97
  • 2
  • 13
CaptainZero
  • 1,431
  • 1
  • 19
  • 38
  • So, what do you want: Given `products = [{ id: 1 }, { id: 2}]`, should the output be `data-ids="1,2"`? – Jack Bashford Apr 16 '19 at 04:52
  • yes, that's what i need without an additional loop – CaptainZero Apr 16 '19 at 04:53
  • 1
    Possible duplicate of [Join JSON Object member string values together](https://stackoverflow.com/questions/12043865/join-json-object-member-string-values-together) – azeós Apr 16 '19 at 04:55
  • @azeós not a possible duplicate, because i need to get it without an additional loop. The answer uses $.map to loop through array – CaptainZero Apr 16 '19 at 04:58
  • 1
    @CaptainAdmin the selected answer user `$.map` function. That's not exactly a loop. – azeós Apr 16 '19 at 05:00
  • you could use JSON.stringify() to add them all and later JSON.parse() to turn it back into an array. – Ekim Apr 16 '19 at 09:14

2 Answers2

2

You can try with map() and .data() like the following way:

var products = [{id: 1},{id: 2},{id: 3},{id: 4}];
var ids = products.map(i => i.id).join(',');
$('.product').parents().data('ids',ids);
console.log($('.product').parents().data());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-ids=""> <!-- parent div -->
  Test
  <div class="product">
  </div>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

var products = [{ id:1 },{ id:2 },{id:3},{id:4}];

    var prod_len=products.length;
    for(let i=0;i<prod_len;i++){
       var div_id=create_html(products[i]['id'])
       $(document).find('.prod_data').append(div_id)
    }

     function create_html(id){
           return `<div data-ids=${id}>
            Product Data ${id}
        <div class="product">
        </div>
       </div>`
    }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="prod_data"></div>


    
Arun Kumar
  • 121
  • 10