Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

How can i add objects from data attribute to an array in javascript?Check below for more specification

But I have a problem. In HTML data attributes, I put some data from php and then I access those data in javascript as an object. I am writing a shopping cart project using js. However for some reasons, I can't put all the objects in an array. Here's my code.

let carts = document.querySelectorAll('.addtocart');
  for(let i=0;i<carts.length; i++){
    let datattr = {
      product_name:carts[i].dataset.name,
      product_tag:carts[i].dataset.name,
      product_price:carts[i].dataset.price,
      product_img:carts[i].dataset.img,
      incart:0
    };
    let products = [];
    console.log(datattr);
question from:https://stackoverflow.com/questions/65546325/how-can-i-add-objects-from-data-attribute-to-an-array-in-javascriptcheck-below

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure what your goal is but you can get all of the data attributes in an array by selecting the elements, setting up an array for the data attributes and looping through the elements, placing the values in your array.

let carts = document.querySelectorAll('.addtocart');
const dataattr = [];
carts.forEach(el => {
  dataattr.push({
    product_name: el.dataset.name,
    product_tag: el.dataset.name,
    product_price: el.dataset.price,
    product_img: el.dataset.img,
  })
});
console.log(dataattr);
.addtocart:before {
  content: attr(data-name);
  font-family: sans-serif;
}
<div class="addtocart" data-name="apple" data-price="1.00" data-img="apple.jpg"></div>
<div class="addtocart" data-name="banana" data-price="0.70" data-img="banana.jpg"></div>
<div class="addtocart" data-name="orange" data-price="2.00" data-img="orange.jpg"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...