Javascript - How to display SessionStorage obj in HTML - javascript

I have object data in sessionStorage and I want to display them as a list in HMTL via loop. How do I Achieve this?
SesionStorage.cart data stringified:
[{"itemName":"WS: FaceShield, 10pcs pack","itemPrice":0,"itemQuantity":"1"},{"itemName":"Faceshield, 1 pc","itemPrice":0,"itemQuantity":"1"}]
What I want to do now is display them on a list after parsing them as JSON Object again.

Say you have
<ul id="myUL"></ul>
Here's a suggestion how to do it in JavaScript by using Array.prototype.reduce into a Web API DocumentFragment that can be later ParentNode.append() -ed into an UL HTMLElement:
// Let's define our array
const arr = [
{"itemName":"WS: FaceShield, 10pcs pack","itemPrice":0,"itemQuantity":"1"},
{"itemName":"Faceshield, 1 pc","itemPrice":0,"itemQuantity":"1"}
];
// Store it into LS...
localStorage.arr = JSON.stringify(arr);
// Read it from LS
const LS_arr = JSON.parse(localStorage.arr);
// Create a helper for new elements...
const ELNew = (sel, attr) => Object.assign(document.createElement(sel), attr || {});
// Loop the array and create LI elements
const LIS = LS_arr.reduce((DF, item) => {
DF.append(ELNew('li', {
textContent: `Name: ${item.itemName} Price: ${item.itemPrice}`
}));
return DF;
}, new DocumentFragment());
// Once our DocumentFragment is populated - Append all at once!
document.querySelector("#myUL").append(LIS);

Related

JS: Iterate through the key, value pairs of an Object

I'm working on a Django framework project where I create a variable in Python to be a dict like:
dict = {
('ABC', 'XYZ'): [
('a', 'A'),
('b', 'B'),
('c', 'C'),
....
]
}
and I am including this data into an HTML's data-attribute when I render the page. When I grab this data in JS is when it gets difficult for me because JS only recognizes tuples like arrays I believe. I need to loop through this object in JS to create my HTML code. Trying something like console.log(Object.entries(obj)) creates thousands of arrays.
In pseudo code, I'm trying to accomplish:
function init(section) {
var test1 = [...create HTML code....]
return new Promise(function (resolve, reject) {
$(section).append(test1)
resolve()
}
$(document).ready(function () {
var section = $("#PageFilter")
var filters = $(section).data("filters")
for (const [key, value] of Object.entries(filters)) {
init(section).then(function () {
for (let x = 0; x < value.length; x++) {
var test2 = [...create some more HTML code...]
$('find_test1').append(test2)
}
}
}
})
UPDATE
Here is a sample of the DOM element's data attribute I was storing
<div
class="ms-auto py-4"
id="PageFilter"
data-filters="{('Region', 'cardinal'): [('EAST', 'EAST'), ('WEST', 'WEST')], ('State', 'state'): [('AL', 'AL'), ('AR', 'AR'), ('GA', 'GA'), ('KY', 'KY'), ('MS', 'MS'), ('NC', 'NC'), ....], ('Instatllation Type', 'installation_type'): [('BUILDING', 'Building'), ('EXTERNAL SERVICE', 'External Service'), ...]}"
></div>
After some clarification, I realize HTML's data attributes were only storing text, and the string was not in the JSON format to be parsed.
I was able to obtain the object in JS by doing a couple of things:
I changed my python dict to the format
{'key': (tuple), 'value': [(tuple), (tuple)]}
...so that JS can distinguish the key, value pair in its object.
I made sure I was using json.dumps(my_python_dict) when I was rendering the page to capture it in JSON.

Traverse all possible paths of an array with javascipt using async

I' am a begginer with Javascript and I am currently try to find all possible paths of a returned JSON object from an axios GET request.Every item can belong to one or more groups, and one group can belong to an other group.
e.g.
{
"name": "item1",
"groupNames": [ "GROUPA" ]
}
{
"name": "GROUPA",
"groupNames": [
"GROUPB"
]
}
....
{
name: "GROUPZ"
"groupNames": [
]
}
My issue is that my code is working only if a item name has only one parent groupName in the array.
What if we have more than one parentgroupNames? e.g
{
"name": "item1",
"groupNames": [ "GROUPA","GROUC",GROUBD ]
}
...
My current code:
let parent = 'item1';
do{
let endpoint = ${process.env.OPENHAB_HOST}:${process.env.OPENHAB_PORT}/rest/items/${parent}?recursive=false
result = await getAxiosRequest(endpoint,{},res); // get request to specific endpoint
parent = result.data.groupNames; }
while(result.data.groupNames.length !== 0 )
To find all the parent groups for an item that has multiple parent groups, you can modify your code as follows:
Initialize an array called parents to store the parent groups that you find.
In the loop, instead of assigning parent to result.data.groupNames, iterate over result.data.groupNames and add each group to the parents array.
After the loop, parents will contain all the parent groups for the given item.
Here's how the modified code would look:
let parent = 'item1';
let parents = []; // initialize array to store parent groups
do {
let endpoint = `${process.env.OPENHAB_HOST}:${process.env.OPENHAB_PORT}/rest/items/${parent}?recursive=false`;
result = await getAxiosRequest(endpoint,{},res); // get request to specific endpoint
result.data.groupNames.forEach(group => parents.push(group)); // add each group to the parents array
parent = result.data.groupNames;
} while(result.data.groupNames.length !== 0);
console.log(parents); // array of parent groups
This should work even if the item has multiple parent groups.
It is not entirely clear what the end result should be after the loop has ran, but I'll assume you would maybe collect the paths from the given item in an array.
As indeed you can get multiple groups, you need to either store them in a queue/stack for later processing, or use recursion (for the same reason).
Here is how it could look with recursion:
function async visit(parent) {
const endpoint = `${process.env.OPENHAB_HOST}:${process.env.OPENHAB_PORT}/rest/items/${parent}?recursive=false`;
const {data} = await getAxiosRequest(endpoint, {}, res);
const results = [];
for (const group of data.groupNames) {
results.push(...(await visit(group)).map(path => path.concat(group)));
}
return results;
}
visit('item1').then(paths => {
// ....
});

Extract unique values of a key in a object - Javascript/d3 legend

Consider the following simplified csv file
x,y,names
1,2,group1
3,2,group2
4,3,group1
7,8,group3
3,5,group2
which I am reading in with d3.csv and afterwards apply a some function on it
d3.csv('file_name.csv').then(data => {
render(dataset)
});
Could someone explain to me how I could extract the unique strings in the category names and store them in a list
---> iam_a_list = [group1, group2, group3]
The elements in this list will later be used as text for a legend in a plot.
You can use a set to get unique results. Just loop over your data and make an array of all the names. Then make a set, which will remove all the duplicates and give you a unique list.
Using .map() and d3.set().values()
let uniqueListOfNames= []
d3.csv('file_name.csv').then(data => {
// listOfNames = ['group1', 'group2', 'group1', 'group3', 'group2']
const listOfNames = data.map(row => row.names)
// uniqueListOfNames = ['group1', 'group2', 'group3']
uniqueListOfNames = d3.set(listOfNames).values()
});
Using a loop.
let uniqueListOfNames= []
d3.csv('file_name.csv').then(data => {
const listOfNames= []
for (const row of data) {
listOfNames.push(row.names)
}
// listOfNames= ['group1', 'group2', 'group1', 'group3', 'group2']
// uniqueListOfNames = ['group1', 'group2', 'group3']
uniqueListOfNames = d3.set(listOfNames).values()
});

How to get result from json object with angular js?

I have a json file and want to count the rows by specific value and load to my page using angular js models.
The json is look like this:
[
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
]
The json file loaded by $http service.
How can I run such query on the json data:
select COUNT(`name`) as a from tbl_ben where ` gender` = 'Female' and `district` = 'LA';
any idea? 
 
You can't run SQL queries on JSON out-of-the-box, so let's work through it in JavaScript.
We have some data in an array, let's call it people:
let people = [
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];
Now, let's filter it down based on their gender and district like in your query:
let filtered = people.filter(p => (p.district === "LA") && (p.gender === "Female"));
Now instead of using COUNT, we can just check the length property of our filtered array:
let count = filtered.length;
We can abstract this code away into a nice function which will do the work for us:
let getCount = (array, predicate) => {
return array.filter(predicate).length;
};
And we can then use this function like so:
let people = [
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];
getCount(people, p => p.district === "NY" && p.gender === "Male"); // 1
Note that based on your example data, the count is 0 as you have nobody in the district "LA".

How to get JSON Data depending on other data values in JavaScript

My Json is like this:
[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
]
I want all the names which have BankOut value as "Y" into an array using JavaScript, in order to use those names in my protractor automation.
You need to use filter method of array. It takes function as it argument. And runs it against each element of array. If function returns true (or other truthy value) then that element stays in newly created array.
var list =[ {"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var onlyBankOutY = list.filter(function (item) {
return item.BankOut === 'Y';
});
document.body.innerHTML = onlyBankOutY.map(function (item) {
return JSON.stringify(item);
}).join('<br>');
var list =[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null}, {"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var names = [];
list.forEach(function(el) {
if (el.BankOut === 'Y') {
names.push(el.name)
}
})

Categories

Resources