简体   繁体   中英

Not Able To Add Values inside a JSON object dynamicaally

I am trying to add objects to a JSON object to be like

 var books = [{
                "no" : 1,
                "bookType":"fiction",
                "bookPrice": 60

            },{
                "no" : 2,
                "bookType":"fun",
                "bookPrice": 40

            }
            ....
  ]

but the out put is so different! can you please let me know how to fix this?

  $(document).ready(function() { var books = []; $('.addItem').on('click', function() { var type = $(this).data('type'); var price = $(this).data('price'); books.push('{',type, '"',price,'"}'), console.log(books); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="addItem" data-type="fiction" data-price="50">Add Book</button> <button class="addItem" data-type="fun" data-price="40">Add Book</button> 

It's because you have inserted string instead of an object. You don't need to stringify an object in order to insert into an array. Array can hold objects.

 $(document).ready(function() { var books = []; $('.addItem').on('click', function() { var type = $(this).data('type'); var price = $(this).data('price'); books.push({ "no":books.length, "bookType":type, "bookPrice":price }); console.log(books); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="addItem" data-type="fiction" data-price="50">Add Book</button> <button class="addItem" data-type="fun" data-price="40">Add Book</button> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM