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?

6
  • So, what do you want: Given products = [{ id: 1 }, { id: 2}], should the output be data-ids="1,2"? Commented Apr 16, 2019 at 4:52
  • yes, that's what i need without an additional loop Commented Apr 16, 2019 at 4:53
  • 1
    Possible duplicate of Join JSON Object member string values together Commented Apr 16, 2019 at 4: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 Commented Apr 16, 2019 at 4:58
  • 1
    @CaptainAdmin the selected answer user $.map function. That's not exactly a loop. Commented Apr 16, 2019 at 5:00

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>


    

Comments

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.