Home > other >  How to add these HTML attributes to a JavaScript object?
How to add these HTML attributes to a JavaScript object?

Time:01-21

I have a list of attributes inside divs that I want to put into an object -

<div >
    <div  product-name="English-One" translated-name="Translated-One"></div>
    <div  product-name="English-Two" translated-name="Translated-Two"></div>
</div>

So I looped through .product-data .product and added each attribute like this -

$('.product-data .product').each(function () {
        translatedProducts = {
            "product": {
                "en": $(this).attr('product-name'),
                "tr": $(this).attr('translated-name')
            }
        }
});

However when I console.log(translatedProducts) I get multiples, and it's only adding English-Two -

Object { product: {…} }
product: Object { en: "English-Two", tr: "Translated-Two" }
en: "English-Two"
tr: "Translated-Two"

How can I write this so that I loop through each div and add the product-name and translated-name attributes to my object?

CodePudding user response:

You are overwritting the same object. Objects cannot have identical keys, so the latter overwrites the former.:

{ product:{}, product:{} } /* => */ { product: {} }

It looks as if you want the objects into one bigger object. If you want both objects, put them in an array:

{ products: [ {}, {} ] }; 

Also, you should use data-* attributes, customized keys is what they are made for.

let products = [];
let translatedProducts = {};

$('.product').each(function(i) {
  let product = {};
  product.en = $(this).data('product');
  product.tr = $(this).data('translated');
  products.push(product);
});

translatedProducts.products = products;

console.log(translatedProducts);
<div >
    <div  data-product="English-One" data-translated="Translated-One"></div>
    <div  data-product="English-Two" data-translated="Translated-Two"></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

Use an array and push each separate set of values to it

var translatedProducts = [];
$('.product-data .product').each(function () {
        translatedProducts.push( {
            "product": {
                "en": $(this).attr('product-name'),
                "tr": $(this).attr('translated-name')
            }
        });
});
  •  Tags:  
  • Related