Show JSON by clicking a button - javascript

How can I show the JSON object that is in the random by clicking the button. With Javascript.
var myObject = {
"catalogo": [
{
"id" : "001",
"name":"Nike",
"desc" : "shoes",
"price": 500,
},
{
"id" : "002",
"name":"MIKEY",
"desc" : "shoes",
"price": 500,
},
{
"id" : "003",
"name":"VANS",
"desc" : "shoes",
"price": 500,
},
{
"id" : "004",
"name":"SPORT",
"desc" : "shoes",
"price": 500,
}
]
};
var random = myObject.catalogo[Math.floor(Math.random()* myObject.catalogo.length)];
document.getElementById('table').innerHTML = random.shortname + "<br>" + "$" + random.price + ".00";
HTML CODE:
Here is the code for the button to display the value.
<div>
<div id="random"></div>
<button>Añadir</button>
</div>
I want to show it here
<div>
<p class="line"></p>
</div>

This is how you would do it.
Take note, you also had some errors in your logic for getting the random data. The table ID doesn't exist (changed to line) and shortname isn't in your data (changed to name)
var myObject = {
"catalogo": [{
"id": "001",
"name": "Nike",
"desc": "shoes",
"price": 500,
},
{
"id": "002",
"name": "MIKEY",
"desc": "shoes",
"price": 500,
},
{
"id": "003",
"name": "VANS",
"desc": "shoes",
"price": 500,
},
{
"id": "004",
"name": "SPORT",
"desc": "shoes",
"price": 500,
}
]
};
function showRandom() {
var random = myObject.catalogo[Math.floor(Math.random() * myObject.catalogo.length)];
document.querySelector('.line').innerHTML = random.name + "<br>" + "$" + random.price + ".00";
}
<div>
<div id="random"></div>
<button onclick="showRandom()">Añadir</button>
</div>
<div>
<p class="line"></p>
</div>

Change your button to <button id="anadir">Añadir</button>.
After doing this, you can get your button from JS after the document loads:
window.addEventListener("DOMContentLoaded", function(event) {
var myAddButtton = document.getElementById('anadir');
myAddButton.onclick = function() {
var random = myObject.catalogo[
Math.floor(Math.random()* myObject.catalogo.length)
];
document.querySelector('.line')
.innerHTML = random.shortname + "<br>" + "$" + random.price + ".00";
}
}
Load this in a <script> tag in your page and it should work.

Related

How can I select children options from optgroup in Select2?

Question:
I have successfully created a select2 template with a group but I can't select the items in it, is there anything missing from the code I made below? Any help from you means a lot to me, thank you
See this first,
Preview Image
For the data below, i folow https://select2.org/data-sources/formats
Result from AJAX :
{
"status": true,
"message": null,
"data": [
{
"text": "Bank",
"children": [
{
"id": "002",
"icon": ".../payment/bri_1.png",
"text": "BANK BRI"
},
{
"id": "008",
"icon": ".../payment/mandiri_1.png",
"text": "BANK MANDIRI"
},
{
"id": "009",
"icon": ".../payment/bni_1.png",
"text": "BANK BNI / SYARIAH"
},
{
"id": "014",
"icon": ".../payment/bca_1.png",
"text": "BANK BCA"
},
{
"id": "022",
"icon": ".../payment/1280px-CIMB_Niaga_logo.svg.png",
"text": "CIMB NIAGA / SYARIAH"
},
{
"id": "016",
"icon": ".../payment/Maybank-Logo.png",
"text": "Maybank"
},
{
"id": "013",
"icon": ".../payment/images.png",
"text": "PERMATA BANK"
},
{
"id": "213",
"icon": ".../payment/Jenius-logo.png",
"text": "Jenius/BTPN"
},
{
"id": "011",
"icon": ".../payment/kissclipart-danamon-logo-png-clipart-bank-danamon-logo-a9b2b21755c37a3a.png",
"text": "Danamon"
},
{
"id": "012",
"icon": ".../payment/images_1.png",
"text": "Bank Neo Commerce/Bank Yudha Bakti"
},
{
"id": "017",
"icon": ".../payment/images-removebg-preview.png",
"text": "Bank Syariah Indonesia"
}
]
},
{
"text": "eMoney",
"children": [
{
"id": "900",
"icon": ".../payment/ovo.png",
"text": "OVO"
},
{
"id": "901",
"icon": ".../payment/gopay.png",
"text": "GOPAY"
},
{
"id": "903",
"icon": ".../payment/dana_1.png",
"text": "DANA"
},
{
"id": "904",
"icon": ".../payment/linkaja.png",
"text": "LINK AJA"
},
{
"id": "906",
"icon": ".../payment/shopeepay-shopee.co.id_ratio-16x9.jpg",
"text": "SHOPEE PAY"
}
]
}
]
}
Code :
$("#payment").select2({
placeholder: 'Payment',
width: 'resolve',
minimumResultsForSearch: Infinity,
templateResult: function formatState(state) {
if (!state.id) return state.text;
var $state = $(
'<span><img src="' + state.icon + '" style="width:30px;"/> ' + state.text + '</span>'
);
return $state;
},
ajax: {
url: base_url + 'user/api/payment',
dataType: 'json',
processResults: function(data) {
return {
results: $.map(data.data, function(item, key) {
var children = [];
for (var k in item.children) {
var childItem = [];
childItem.id = item.children[k].id;
childItem.icon = item.children[k].icon;
childItem.text = item.children[k].text;
children.push(childItem);
}
return {
text: item.text,
children: children,
}
})
};
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Payment</label>
<div class="col-sm-10">
<select name="payment" id="payment" class="form-control">
</select>
</div>
</div>
As far as I can see in your code, your API is returning results already formatted, so keep it simple. Please check this fiddle with a fully working example based on your code.
$("#payment").select2({
placeholder: 'Payment',
width: 'resolve',
ajax: {
url: 'https://randomuser.me/api/', //a random URL to simulate a request response in jsfiddle
dataType: 'json',
processResults: (data) => ({ results: response.data })
}
});

How do I filter products based on category using jquery given that they are on two separate json files?

Okay, this is a little tricky on my side. I have two json files, food.json and rest_category.json. I am trying to find a way to filter the foods in food.json based on the category in rest_category.json. I got an idea that perhaps I should add a foreign_id in food.json that matches the id in category in rest_category.json. Still, how do I proceed from there? Is there a way that I could attempt this? I'd really appreciate it. Thanks
Below is a sample of my food.json and rest_category.json.
food.json
[
{
"id":"1",
"Name":"Coke 500ml",
"Price":"80",
"Quantity": "50",
"Category":"Beverages"
},
{
"id":"2",
"Name":"Cake",
"Price":"150",
"Quantity": "40",
"Category":"Appetizer"
},
{
"id":"3",
"Name":"Beef Ribs",
"Price":"100",
"Quantity": "50",
"Category":"Side Items"
},
{
"id":"4",
"Name":"Cabbage Salad",
"Price":"50",
"Quantity": "30",
"Category":"Salads"
},
{
"id":"5",
"Name":"Cake",
"Price":"150",
"Quantity": "30",
"Category":"Appetizer"
},
{
"id":"6",
"Name":"Beef Ribs",
"Price":"100",
"Quantity": "30",
"Category":"Side Items"
}
]
rest_category.json
[
{
"id" : "1",
"name" : "Appetizers",
"Status" : "Active"
},
{
"id" : "2",
"name" : "Salads",
"Status" : "Active"
},
{
"id" : "3",
"name" : "Entrees",
"Status" : "Active"
},
{
"id" : "4",
"name" : "Side Items",
"Status" : "Active"
},
{
"id" : "5",
"name" : "Beverages",
"Status" : "Active"
}
]
Just to add, the response should be displayed on a HTML page. I am currently able to append a list of categories and foods. Stuck on the filter section.
Below is my sample code I used to append the categories and food.
// display products from json file
$(document).ready(function() {
$.getJSON("../json/food.json", function(data) {
var food_data = '';
$.each(data, function(key, value) {
food_data += '<div id = "product_sect" class = "product">'
food_data += '<a href = "#"> <img class = "food-image" src =
"../images/dinner.svg"></a>'
food_data += '<p style = "margin:0;" id = "FoodName">' +
value.Name + '<p class = "p_quantity" id = FoodQuantity>' + 'Qty:' +
value.Quantity + '</p>' + '<p class = "p_price" id = "FoodPrice">' +
value.Price + "/=" + '</p>' + '</p>'
food_data += '<a id = "cart-click" class = "btn btn-primary add-
to-cart" href = "#" data-id= + "'+value.ID+'">Add to Cart</i></a>'
food_data += '</div>'
});
$('#product_grid').append(food_data)
});
});
//display categories from json file
$(document).ready(function() {
$.getJSON("../json/rest_category.json", function(data) {
var cat_data = '';
$.each(data, function(key, value) {
cat_data += '' + value.name + ''
});
$('#rest_category').append(cat_data)
});
});
You should give a try to Array.filter() method:
const arr = [
{
"id": "1",
"Name": "Coke 500ml",
"Price": "80",
"Quantity": "50",
"Category": "Beverages"
},
{
"id": "2",
"Name": "Cake",
"Price": "150",
"Quantity": "40",
"Category": "Appetizer"
},
{
"id": "3",
"Name": "Beef Ribs",
"Price": "100",
"Quantity": "50",
"Category": "Side Items"
},
{
"id": "4",
"Name": "Cabbage Salad",
"Price": "50",
"Quantity": "30",
"Category": "Salads"
},
{
"id": "5",
"Name": "Cake",
"Price": "150",
"Quantity": "30",
"Category": "Appetizer"
},
{
"id": "6",
"Name": "Beef Ribs",
"Price": "100",
"Quantity": "30",
"Category": "Side Items"
}
];
function filterArrayByCategory(category) {
return arr.filter(el => el.Category === category);
}
console.log(filterArrayByCategory('Appetizer'));
Just use Array.map and Array.filter:
let products = [
{
"id":"1",
"Name":"Coke 500ml",
"Price":"80",
"Quantity": "50",
"Category":"Beverages"
},
{
"id":"2",
"Name":"Cake",
"Price":"150",
"Quantity": "40",
"Category":"Appetizer"
},
{
"id":"3",
"Name":"Beef Ribs",
"Price":"100",
"Quantity": "50",
"Category":"Side Items"
},
{
"id":"4",
"Name":"Cabbage Salad",
"Price":"50",
"Quantity": "30",
"Category":"Salads"
},
{
"id":"5",
"Name":"Cake",
"Price":"150",
"Quantity": "30",
"Category":"Appetizer"
},
{
"id":"6",
"Name":"Beef Ribs",
"Price":"100",
"Quantity": "30",
"Category":"Side Items"
}
];
let categories = [
{
"id" : "1",
"name" : "Appetizers",
"Status" : "Active"
},
{
"id" : "2",
"name" : "Salads",
"Status" : "Active"
},
{
"id" : "3",
"name" : "Entrees",
"Status" : "Active"
},
{
"id" : "4",
"name" : "Side Items",
"Status" : "Active"
},
{
"id" : "5",
"name" : "Beverages",
"Status" : "Active"
}
];
let result = categories.map(c=>{
return {
...c,
products : products.filter(p=>p.Category===c.name)
}
})
console.log(JSON.stringify(result,null,2));
In order to help you to achieve your goals I'm going to add another answer, which will show you another approach. Please use it as a reference and adapt to your code based on your current implementation:
const hardCodedFood = [
{
"id": "1",
"Name": "Coke 500ml",
"Price": "80",
"Quantity": "50",
"Category": "Beverages"
},
{
"id": "2",
"Name": "Cake",
"Price": "150",
"Quantity": "40",
"Category": "Appetizer"
},
{
"id": "3",
"Name": "Beef Ribs",
"Price": "100",
"Quantity": "50",
"Category": "Side Items"
},
{
"id": "4",
"Name": "Cabbage Salad",
"Price": "50",
"Quantity": "30",
"Category": "Salads"
},
{
"id": "5",
"Name": "Cake",
"Price": "150",
"Quantity": "30",
"Category": "Appetizer"
},
{
"id": "6",
"Name": "Beef Ribs",
"Price": "100",
"Quantity": "30",
"Category": "Side Items"
}
];
const $categories = $('#categories');
const $availableFoodByCategory = $('#availableFoodByCategory');
hardCodedFood.forEach(el => {
let $option = $('<option/>', {
value: el.Category,
text: el.Category
});
$option.appendTo($categories)
});
$categories.on('change', function() {
$availableFoodByCategory.empty();
hardCodedFood
.filter(el => el.Category === $(this).val()) // filtering dynamically based on category provided
.forEach(el => {
let $row = $('<tr/>');
$('<td/>', {
text: el.id
}).appendTo($row);
$('<td/>', {
text: el.Name
}).appendTo($row);
$('<td/>', {
text: el.Price
}).appendTo($row);
$('<td/>', {
text: el.Quantity
}).appendTo($row);
$row.appendTo(availableFoodByCategory);
});
$availableFoodByCategory.show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='categories'></select>
<table id='availableFoodByCategory' style='display:none;'>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Jquery multiply input number value and Json data

I have a time calculation tool which you can find in the following fiddle link. Once someone has selected a platform, task type, component and number of units, the number of units entered should be multiplied with selected component value and show it on the below table. I have managed to get the all populated values but can't do the math. I have tried several attempts but it wasn't working.
var myJson = {
"platforms": [
{
"name": "Sitecore",
"id": "sitecore",
"tasktype": [
{
"name": "Promobox",
"id": "promobox",
"components": [
{
"name": "Accordion",
"id": "accordion",
"time": "20"
},
{
"name": "Box 1",
"id": "box1",
"time": "30"
}
]
},
{
"name": "Video",
"id": "video",
"components": [
{
"name": "Box 2",
"id": "box2",
"time": "25"
},
{
"name": "Box 3",
"id": "box3",
"time": "30"
}
]
}
]
},
{
"name": "Siab",
"id": "siab",
"tasktype": [
{
"name": "Newswire",
"id": "newswire",
"components": [
{
"name": "Box 4",
"id": "box5",
"time": "50"
},
{
"name": "Box 5",
"id": "box5",
"time": "40"
}
]
},
{
"name": "Task Type New",
"id": "tasktypenew",
"components": [
{
"name": "Box 6",
"id": "box6",
"time": "20"
},
{
"name": "Box 7",
"id": "box7",
"time": "100"
}
]
}
]
}
]
};
$.each(myJson.platforms, function (index, value) {
var platform_id;
var tasktype_id;
var component_id;
$("#platform").append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$("#platform").change(function () {
$("#tasktype, #component").find("option:gt(0)").remove();
$("#tasktype").find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function (index1, value1) {
$("#tasktype").find("option:first").text("Select Task Type");
$("#tasktype").append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$("#tasktype").change(function () {
$("#component").find("option:gt(0)").remove();
$("#component").find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function (index2, value2) {
$("#component").find("option:first").text("Select Component");
$("#component").append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
$(document).ready(function () {
$('#calculate').click(function () {
$('#calc input, #calc select').each(
function (index) {
var input = $(this);
$('#data tbody').append('<tr><td>' + input.val() + '</td></tr>');
});
});
});
JS Fiddle
Ok this took a lot of debugging. You were building your table wrong and not storing data properly. The whole fishing for data was problematic. Here is the debugged calculator:
$(document).ready(function () {
$('#calculate').click(function () {
let tr = $("<tr/>").appendTo("#data tbody");
console.log(tr);
$('#calc input, #calc select').each( function (index) {
console.log($(this));
var input = $(this);
$(tr).append('<td class=row-'+ $(input).attr("id") + '>' + input.val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor*units;
$(tr).append('<td>' + total + '</td>');
});
});
notice:
Change of table structure format.
Now appending td's to single tr each time in order to sustain table-row consistency.
Fishing data from row with the help of adding class tag identifier to each td
Showing result.
update fiddle link:
https://jsfiddle.net/x4rLuf88/1/

remove duplicate value existing object from multidimensional array object in javascript

This is my javascript array:
[{
"id": "44",
"name": "chathura"
}, {
"id": "45",
"name": "gayan"
}, {
"id": "48",
"name": "sunimal"
}, {
"id": "47",
"name": "chathura"
}, {
"id": "20",
"name": "yasith"
}, {
"id": "21",
"name": "thisaru"
}, {
"id": "42",
"name": "insaf"
}, {
"id": "63",
"name": "sunimal"
}, {
"id": "78",
"name": "yasith"
}, {
"id": "36",
"name": "thisaru"
}]
I want to remove duplicate name existing object element from this array and get the following:
[{
"id": "47",
"name": "chathura"
}, {
"id": "45",
"name": "gayan"
}, {
"id": "48",
"name": "sunimal"
}, {
"id ": "20",
"name ": "yasith "
}, {
"id ": "21 ",
"name ": "thisaru"
}, {
"id ": "42 ",
"name ": "insaf"
}]
How can I remove duplicates?
You can iterate through the array and use a hash table to filter any IDs that have already been used:
function getUniqueNames(nameObjects) {
var existingIds = { };
return nameObjects
.filter(function(nameObject) {
var id = nameObject.id;
var alreadyExists = existingIds[id];
existingIds[id] = true;
return alreadyExists;
});
I'm not sure about your use case, but it might make sense in your case just to convert the data into a Map. Maps work similar to a hash table, and will map each name to its ID. They enforce uniqueness by design:
var names = nameObjects
.reduce(function(map, nameObject) {
map.set(nameObject.id, nameObject.name);
return map;
}, new Map());
// Look up a name by ID
names.get(47);
// Do something for every name
names.forEach(function(name, key) {
console.info(name, 'has ID', key);
});
Maps are ES6 and you may need a polyfill for some browsers.
Try this worked solution, using push method :
JS :
var arr = {};
for ( var i=0; i < x.length; i++ )
arr[x[i]['name']] = x[i];
var result = new Array();
for ( var key in arr )
result.push(arr[key]);
That will return an array of objects result that contain a non duplicated objects.
Result :
[{
"id": "47",
"name": "chathura"
}, {
"id": "45",
"name": "gayan"
}, {
"id": "48",
"name": "sunimal"
}, {
"id ": "20",
"name ": "yasith "
}, {
"id ": "21 ",
"name ": "thisaru"
}, {
"id ": "42 ",
"name ": "insaf"
}]
Hope this will help.

Jquery : transform nested json object to another json object

In javascript/jquery how do i achieve following
old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
Using jquery iterate over the above and change to following
new_dataset = [
{
"dob":"xyz",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
},{
"dob":"er",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
}]
If someone can give the code to transform the data it would help me to understand the iteration
You could do something like:
function transformDataset(oldDataset) {
var newDataset = [];
var newObj;
for (var i = 0; i < oldDataset.length; i++) {
newObj = transformObj(oldDataset[i]);
newDataset.push(newObj);
}
return newDataset;
}
function transformObj(obj) {
var children = obj.children;
obj.name = obj.name.first + ' ' + obj.name.last;
obj.start_date = obj.start_date.month + ' ' + obj.start_date.day + ' ' + obj.start_date.year;
obj.children = [];
for (var i = 0; i < children.length; i++) {
obj.children.push(children[i].child.id);
}
return obj;
}
var new_dataset = transformDataset(old_dataset);
Note that new_dataset will have an array of child id instead of an object with multiple child_id properties.
You also had a typo in old_dataset.start_date.month (was written moth)(or maybe that was intentional).
use map first to iterate the array data (old_dataset), replace element name & start_date with new value then return the array
const old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
let new_dataset = old_dataset.map((arr) => {
arr.name = `${arr.name.first} ${arr.name.last}`
arr.start_date = `${arr.start_date.moth} ${arr.start_date.day} ${arr.start_date.year}`
return arr
})
console.log(new_dataset)

Categories

Resources