Reputation: 397
I have a list of products on a site that needs to be translated. In my HTML markup I have this -
var translatedPs = {
"Apple": "Manzana",
"Banana": "Platano",
"Pear": "Pera"
}
$('.products').each(function(index, el) {
let companyProducts = [];
companyProducts.push(($(this).data('products')).split(',').map(el => el.trim()))
let translatedProducts = [];
console.log('Company Products Array', companyProducts)
$.each(companyProducts, function(index, product) {
console.log('Product from Loop:', product[index])
translatedProducts.push(translatedPs[product])
if (typeof translatedPs[product] != 'undefined') {
translatedProducts.push(translatedPs[product])
} else {
translatedProducts.push(product)
}
});
$(el).text(translatedProducts.toString().replace(/,/g, ", "));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="products" data-products="Apple, Banana, Pear"></span>
The code for the companyProducts array is because I have my data in the HTML data-products attribute. So I am converting the string to an array, separating it by a comma, then the map with the trim is to remove any spaces.
My first console log "Company Products Array" returns the correct array -
0: Array [ "Apple", "Banana", "Pear" ]
After this I am looping through the array, comparing it to the data in my object, and if it matches add it to an new array, and then adding this array to the HTML.
However in my console log for "product[index]" it is only retrieving the first item from the array.
Why is it not outputting each item from the array?
Upvotes: 0
Views: 101
Reputation: 338148
You already had an Array#map()
for trimming the original product names.
Do another one.
const translatedPs = {
"Apple": "Manzana",
"Banana": "Platano",
"Pear": "Pera"
};
$('.products').each(function () {
let companyProducts = $(this).data('products').split(',').map(el => el.trim());
let translatedProducts = companyProducts.map(p => translatedPs[p] || p);
$(this).text(translatedProducts.join(', '));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="products" data-products="Apple, Banana, Pear"></span>
Take-away - this is usually not necessary:
var items = [];
listOfThings.forEach(function (thing) {
items.push(convert(thing));
});
and can be replaced by
var items = listOfThings.map(thing => convert(thing));
or even:
var items = listOfThings.map(convert);
where convert
stands for any function that takes a thing
and returns a converted thing, e.g. like so:
const translate = product => translatedPs[product];
let translatedProducts = companyProducts.map(translate);
Upvotes: 1