Display related products in javascript - javascript

I need to display related products in javascript on eBay listing.
I have that idea: I keep in array info about other listings like: url, image, price and tags attached to this product.
example:
some_product = [
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
],
some_product_2 = [
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
]
and on listing I put code like:
<script type="text/javascript" src="http://domain.com/related_prod.js?keyword=home"></script>
And I expect that showed all the products with "home" in "tags". Can someone direct me to a solution?

First off, this is not a valid JavaScript or JSON:
some_product = [
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
],
some_product_2 = [
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
]
The above should be replaced with the { } for objects.
{
some_product: {
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
},
some_product_2: {
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
}
}
The above is a JavaScript object now. But this has been made better. Now, this being a pure JSON, it has to be added to a JavaScript variable. Consider this:
var products = {
some_product: {
tags: 'home, garden, kitchen',
url: http://listing.url,
price: 100
},
some_product_2: {
tags: 'home, lifestyle, books',
url: http://listing2.url,
price: 120
}
}
Now using the products, you can loop and put it as a list item.
var products = {
some_product: {
tags: 'home, garden, kitchen',
url: 'http://listing.url',
price: 100
},
some_product_2: {
tags: 'home, lifestyle, books',
url: 'http://listing2.url',
price: 120
}
}
var finalHtml = "";
for (var item in products) {
finalHtml += '<li><a href="' + products[item].url + '">' + item + '<\/a> <br \/>Tags: ' + products[item].tags + '<br \/>Price: ' + products[item].price + ' $</li>';
}
document.getElementById("products").innerHTML = finalHtml;
<ul id="products"></ul>
See the snippet above.

Considering that's not valid JavaScript, we can restructure your code to something more usable for your scenario... Like this:
var products = [
{
name: 'some_product',
tags: ['home', 'garden', 'kitchen'],
url: 'http://example.com/1',
price: 100,
},
{
name: 'some_product_2',
tags: ['home', 'lifestyle', 'books'],
url: 'http://example.com/2',
price: 120,
}
];
From here, we can use Array.prototype.filter to fetch the results based on tags:
function category(tag) {
return products.filter(function(product){
if (~product.tags.indexOf(tag)) return product;
});
}
category('home');
// ...
Example

both Praveen Kumar and Jamen proved to be helpful. I joined their answers to create one code.
var products = [
{
name: 'some_product',
tags: ['home', 'garden', 'kitchen'],
url: 'http://example.com/1',
price: 100,
},
{
name: 'some_product_2',
tags: ['home', 'lifestyle', 'books'],
url: 'http://example.com/2',
price: 120,
},
{
name: 'some_product_3',
tags: ['garden', 'lifestyle', 'books'],
url: 'http://example.com/2',
price: 120,
}
];
var finalHtml = "";
function category(tag) {
return products.filter(function(product){
if (~product.tags.indexOf(tag)) {
finalHtml += '<li><a href="' + product.url + '">' + product.name + '<\/a><br \/>Price: ' + product.price + ' $</li>';
document.getElementById("products").innerHTML = finalHtml;
console.log(product.name);
}
});
}
category('home');
//category('garden');
<ul id="products"></ul>
https://jsfiddle.net/p5x2v2cb/
Thank you for answers.

Related

Match array object with text of element

I have an array of objects which all follow the same format and another array of objects
Using the following code, I am able to generate the subheadings with no issues. However what I would like to have is subheadings separating the generated services. The subheadings separations are based on the services[k].category.
This is what I have so far, however it is not working. The subheadings generate without issue, however the rest is not working:
let categories = [{
name: "Logo and Branding"
},
{
name: "Web Design"
},
{
name: "Print"
},
{
name: "Presentations"
},
{
name: "Art & Illustration"
},
{
name: "Animation"
}
]
let services = [{
"name": "Logo",
"description": "Capture the essence of your brand with an unforgettable logo design.",
"icon": "logo.svg",
"category": "logo"
}]
function generateServices(amount) {
var content = "";
for (let q = 0; q < categories.length; q++) {
content += '<div class="col-12 main_titleCol"><div class="main_title"><h2 class="servicestitle">' + categories[q].name + '</h2></div></div>';
}
$('.services').html(content);
let servicesheading = $('.servicestitle');
// add the new items
for (let k = 0; k < amount; k++) {
console.log(servicesheading.html);
if (servicesheading.innerText == services[k].description) {
content += '<div class="col-lg-4 col-md-4"><div class="feature_item"><img class="img-fluid services-icon" src="img/services/SVG/' + services[k].icon + '"><h4>' + services[k].name + '</h4><p>' + services[k].description + '</p></div></div>';
}
}
}
generateServices(10)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="services"></div>
The final outcome should look like this if all were to work:
1. Let's group our initial array of services by category:
const services = [
{ name: '...', category: '...', 'description': '...', 'icon': '...' },
{ name: '...', category: '...', 'description': '...', 'icon': '...' },
{ name: '...', category: '...', 'description': '...', 'icon': '...' },
...
];
const servicesByCategory = services.reduce((acc,el) => {
if (acc[el.category]) acc[el.category].push(el)
else acc[el.category] = [el];
return acc;
}, {});
servicesByCategory is an object where keys are service categories and values are arrays of services assigned to category:
{
service1: [ { name: '...', ... }, ... ],
service2: [ { name: '...', ... }, ... ],
service3: [ { name: '...', ... }, ... ],
...
}
2. Now you can process services one by one for each category:
let content = '';
for (let category in servicesByCategory) {
// Do what you want with category name
// Let's add category header as an example
content += '<div class="col-12 main_titleCol"><div class="main_title"><h2 class="servicestitle">' + category + '</h2></div></div>';
for (let service of servicesByCategory[category]) {
// Proccess services one-by-one as you did before
content += '<div class="col-lg-4 col-md-4"><div class="feature_item"><img class="img-fluid services-icon" src="img/services/SVG/' + service.icon + '"><h4>' + service.name + '</h4><p>' + service.description +'</p></div></div>';
}
}

How do I replace with filter function to the following for looping in JavaScript

how do I replace the for loop with .filter function in JavaScript.The matched name appears in the list.
let originalMoviesList = [ //Contains moviesname and url
{
name: "War Horse",
url: "War_Horse.jpg",
tag: "lepsum lepsum lepsum lepsum"
},{
name: "War Horse",
url: "War_Horse.jpg",
tag: "lepsum lepsum lepsum lepsum"
}
]
**let** matchedTerms = [];//`array for storing the matched terms`
searchTerm = searchTerm.toLowerCase();
for (let i = 0; i < originalMoviesList.length; i++) {
if ((originalMoviesList[i].name).toLowerCase().indexOf(searchTerm) !== -1) {
matchedTerms.push({//pushing into the array
name: originalMoviesList[i].name,//pushing name to the array of objects
url: originalMoviesList[i].url//pushing url to the array of objects
});
}
}
You are almost there. You just needed to put the condition inside the filter function
let originalMoviesList = [ //Contains moviesname and url
{
name: "War Horse",
url: "War_Horse.jpg",
tag: "lepsum lepsum lepsum lepsum"
}, {
name: "Star Horse",
url: "War_Horse.jpg",
tag: "lepsum lepsum lepsum lepsum"
}, {
name: "War Horse",
url: "War_Horse.jpg",
tag: "lepsum lepsum lepsum lepsum"
}
]
searchTerm = "star"; //searchTerm.toLowerCase();
let matchedTerms = originalMoviesList.filter(function(i) {
return i.name.toLowerCase().indexOf(searchTerm) > -1;
});
That filter can also be written with a fat arrow in EcmaScript 6 compatible code.
let originalMoviesList = [
{
name: "War Horse",
url: "War_Horse.jpg",
tag: "horse war"
},
{
name: "War Dolphin",
url: "War_Dolphin.jpg",
tag: "dolphin war"
}
];
let searchTerm = 'Horse';
let matchedTerms = originalMoviesList.filter( (movie) => movie.name
.toLowerCase()
.includes(searchTerm.toLowerCase()));
console.log(matchedTerms);

Splitting text based on its offset value and push it to new object

I wanted to break down paragraph based on it’s entityRanges.
So the actual paragraph looks like this,
{
type: 'paragraph',
depth: 1,
text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.',
entityRanges: [{
type: 'LINK',
offset: 83,
length: 16,
data: {
target: '_self',
url: '/index.htm'
}
}]
}
But my expected results should be like below,
{
type: 'paragraph',
depth: 1,
text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.',
entityRanges: [{
type: 'LINK',
offset: 83,
length: 16,
data: {
target: '_self',
url: '/index.htm'
}
}],
embbeded: [{
type: 'text',
text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our '
}, {
type: 'link',
text: 'customer support',
data: {
target: '_self',
url: '/index.htm'
}
}, {
type: 'text',
text: 'page.'
}]
}
I wanted to break down the text into multiple parts based on it’s offset & length values.
As per the example, customer support is the offset value.
So it should breakdown in the below order
Do you have questions or comments and do you wish to contact ABC?
Please visit our
customer support
page.
All above parts needs to pushed to new object embbeded.
I hope that I understood you correctly:
const data = {
"text": "Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.",
"entityRanges": [{
"type": "LINK",
"offset": 83,
"length": 16,
"data": {
"target": "_self",
"url": "/index.htm"
}
},
{
"type": "LINK",
"offset": 7,
"length": 4,
"data": {
"target": "_self",
"url": "/index.htm"
}
}
]
};
function breakData(data) {
let {
entityRanges,
text
} = data;
const result = [];
let finalPart = '';
let index = 0;
entityRanges
.sort((a, b) => a.offset - b.offset)
.forEach((styleRange) => {
const {
offset,
length,
type,
data
} = styleRange;
const firstPart = text.substring(index, offset);
result.push({
type: 'text',
text: firstPart,
});
index = offset + length; // + 1;
const secondPart = text.substring(offset, index);
result.push({
type,
data,
text: secondPart,
});
finalPart = text.substring(index);
});
if (finalPart) {
result.push({
type: 'text',
text: finalPart,
});
}
data.embbeded = result;
return data;
}
const result = breakData(data);
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, ' ') + '</pre>';

Parse Database JavaScript and PhoneGap

I've been working on an restaurant app that should get the menu from an online database.
This is how I currently and "Manually" populate the menu:
Controller.html
$scope.menu = [{
name: 'Espresso',
price: 27,
qty: 1,
desc: "One shot of espresso prepared with 7 grams of ground coffee in a single portafilter. The shot should be 1 ounce of liquid. You have two choices with espresso: ristretto, a very short or “restrained” shot, brewed at less than 2/3 of a demitasse, or luongo, a long pull of espresso brewed so the liquid should be more than 2/3 of a demitasse.",
img: "img/espresso.png",
active: false,
sizes: [{name: "Small", price: 0, active:false},
{name: "Medium", price: 5, active:false},
{name: "Large", price: 10, active:false}],
flavors: [{name: 'Vanilla', price: 8, active: false},
{name: 'Almond', price: 8, active: false},
{name: 'Hazelnut', price: 8, active: false},
{name: 'Caramel', price: 8, active: false}]
}];
However I can't seem to achieve populating this using Parse, how would I approach this using a query as the following (Which is a working query).
Index.html
<script type="text/javascript">
Parse.initialize("vGoJDvwwfZBiUFcwfkee7M5vCqL7lLxCgKIFJXDc", "6VRlos6qppaek1uDPPLqpHtmB3fHefOJMqYJNxj9");
var DrinkMenu = Parse.Object.extend("DrinkMenu");
var query = new Parse.Query(DrinkMenu);
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " items.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('name'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
You can notice I can get the variables needed for each item, in this case the name of the first result, which I display in an alert.
Any help is appreciated!
After Parse.initialize, create a variable, like this:
var arrMenu = [];
then change the line alert(object.id + ' - ' + object.get('name')); to
arrMenu.push({
name: object.get('name'),
price: object.get('price'),
qty: object.get('qty'),
desc: object.get('desc'),
img: object.get('img'),
active: object.get('active'),
sizes: object.get('sizes'),
flavors: object.get('flavor')
});
I am supposing that you are storing the info in the Parse Collection with the structure you mentioned. If it is different, let me know.
And, after the brack the closes the for, you add:
$scope.menu = arrMenu;
I hope it helps!

How do I add an image to an javascript array?

I have a page with a search bar that has auto complete according to the data in a separate js file. If I type in a letter it throws out the related names that starts with or contains that letter, if I select the result if displays the details that come with that name. I just need to know how to link an an image to that data so when selected a picture is displayed with that info of the name.
Here is my Javascript code:
$(function(){
var currencies = [
{ value: 'Murray Smith', data: 'AFN', foto: src='img/logo.jpg' },
{ value: 'Brown Church', data: 'ALL' ,foto: src='../img/logo.jpg'},
{ value: 'Jack Jones', data: 'DZD' ,foto: src='../img/logo.jpg'},
{ value: 'Ben Clark', data: 'EUR' ,foto: src='../img/logo.jpg'},
{ value: 'Pete White', data: 'AOA' ,foto: src='../img/logo.jpg'},
{ value: 'East Caribbean dollar', data: 'XCD' ,foto: src='../img/logo.jpg'},
];
// setup autocomplete function pulling from currencies[] array
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Currency Name:</strong> ' + suggestion.value + ' <br> <strong>Symbol: </strong> ' + suggestion.data + '<br> <strong>Profile Pic:</strong> ' + suggestion.foto;
$('#outputcontent').html(thehtml);
}
});
});
Thank you in advance.
Use this code:
var thehtml = '<strong>Currency Name:</strong> ' + suggestion.value
+ ' <br> <strong>Symbol: </strong> ' + suggestion.data
+ '<br> <strong>Profile Pic:</strong> <img ' + suggestion.foto +' />';
^^^ use image tag here
And your foto should be like this:
foto: "src='img/logo.jpg'"
^^^ add the double quotation mark to make it correct
Updated your array to be valid will help :)
var currencies = [
{ value: 'Murray Smith', data: 'AFN', foto: '<img src="img/logo.jpg">' },
{ value: 'Brown Church', data: 'ALL' ,foto: '<img src="img/logo.jpg">'},
{ value: 'Jack Jones', data: 'DZD' ,foto: '<img src="img/logo.jpg">'},
{ value: 'Ben Clark', data: 'EUR' ,foto: '<img src="img/logo.jpg">'},
{ value: 'Pete White', data: 'AOA' ,foto: '<img src="img/logo.jpg">'},
{ value: 'East Caribbean dollar', data: 'XCD' ,foto: '<img src="img/logo.jpg">'},
];
As André Dion mentioned in his comment, your syntax is invalid.
you should change the foto property value of your object to be:
foto: 'path/to/my/img.ext'
and in your HTML, when calling that property, append it inside an image tag.
thehtml += '<img src="'+foto+'" alt="don't forget the blind!" />';
Hope this helps.
&dash; Sid

Categories

Resources