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?
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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.