Parsing data from api in javascript - javascript

I am trying to parse data from a wordpress json api to my ionic app, Data from api is coming as:
{
"event_0_date_from":["20191015"],
"event_0_date_to":["20190926"],
"event_0_event":["Winter Vacation"],
"event_0_description":["Winter vacation"],
"event_1_date_from":["20190917"],
"event_1_date_to":["20190930"],
"event_1_event":["Dashain Vacation"],
"event_1_description":["--some-data--"],
"event_2_date_from":["--some-data--"],
"event_2_date_to":["--some-data--"],
"event_2_event":["--some-data--"],
"event_2_description":["--some-data--"],
---------------
-------------
--------------
-------------
"event":["3"] this shows total number of events
}
Using javascript, how would I format the above data and save it to some variable so that I can render it easily?
events:[
{
"date_from":"20191015",
"date_to":"20190926",
"event":"Winter Vacation",
"description":"Winter vacation"
},
{
"date_from":"20191015",
"date_to":"20190926",
"event":"Winter Vacation",
"description":"Winter vacation"
},
{
"date_from":"--some-data--",
"date_to":"--some-data--",
"event":"--some-data--",
"description":"--some-data--"
},
---------------
-------------
--------------
-------------
]
I tried so many methods but none are working.

I think your just should take "yourObjekt.event[0]" for a counter like:
var newObjekt = [];
for (var i=0; i<yourObjekt.event[0]; i++) {
newObjekt[i] = {
date_from: yourObjekt["event_"+i+"_date_from"][0],
date_to: yourObjekt["event_"+i+"_date_to"][0],
event: yourObjekt["event_"+i+"_event"][0],
description: yourObjekt["event_"+i+"_description"][0]
}
}

You just need to iterate over your json object. Within each iteration create a new map and push this newly created map into an array. Following is working snippet.
let data = {
"event_0_date_from":["20191015"],
"event_0_date_to":["20190926"],
"event_0_event":["Winter Vacation"],
"event_0_description":["Winter vacation"],
"event_1_date_from":["20190917"],
"event_1_date_to":["20190930"],
"event_1_event":["Dashain Vacation"],
"event_1_description":["--some-data--"],
"event_2_date_from":["--some-data--"],
"event_2_date_to":["--some-data--"],
"event_2_event":["--some-data--"],
"event_2_description":["--some-data--"],
"event":["3"]
}
let array = [];// Initialize an array
let index = data.event[0];// Number of events
for(let i=0;i<index;i++){
let map = {};//Initialize a new map in each iteration.
map.date_from = data["event_"+i+"_date_from"][0];
map.date_to = data["event_"+i+"_date_to"][0];
map.event = data["event_"+i+"_event"][0];
map.description = data["event_"+i+"_description"][0]
array.push(map);// finally push map into array
}
console.log(array);

Try this code, it will include all event attributes in a dynamic way
var output = [];
for(var key in datas){
// parse key
var keyParts = key.split('_');
var value = datas[key];
// ignore "event" total
if(keyParts.length > 1){
var key = keyParts.slice(2).join('_'); // generate correct key from parts
var index = keyParts[1]; // indexes : 0, 1, 2, etc.
// initialize in first call
if(output.hasOwnProperty(index) === false){
output[index] = {}
}
// append to output
output[index][key] = value
}
}

Withing 20 minutes with Googling (+ few minutes for proper adjustment of counters) ... (wrote JS few times in whole life)
I was not sure how to load it into String and did not wanted to escape whole string, so I am loading it from a text file
Input data:
{
"event_0_date_from":["20191015"],
"event_0_date_to":["20190926"],
"event_0_event":["Winter Vacation"],
"event_0_description":["Winter vacation"],
"event_1_date_from":["20190917"],
"event_1_date_to":["20190930"],
"event_1_event":["Dashain Vacation"],
"event_1_description":["--some-data--"],
"event_2_date_from":["--some-data--"],
"event_2_date_to":["--some-data--"],
"event_2_event":["--some-data--"],
"event_2_description":["--some-data--"]
}
Page and script:
<!DOCTYPE HTML>
<html>
<body>
<input type="file" id="upload">
<script>
document.getElementById('upload').addEventListener('change', readFileAsString)
function readFileAsString() {
var files = this.files;
if (files.length === 0) {
console.log('No file is selected');
return;
}
var reader = new FileReader();
reader.onload = function(event) {
//console.log('File content:', event.target.result);
var inputStr = event.target.result;
//console.log(inputStr);
var obj = JSON.parse(inputStr);
//console.log(obj);
var hasNext=true;
var counter = 0;
while(hasNext){
var properties =["date_from","date_to","event","description"];
var propertyPrefix = "event_"
var prop = propertyPrefix + counter + "_" + properties[0];
if(obj.hasOwnProperty(prop)){
console.log("element #" + counter + ": ")
for(var i = 0; i< properties.length;i++){
var propToPrint = propertyPrefix + counter + "_" + properties[i];
//console.log("loading: " + propToPrint)
console.log(" " + obj[propToPrint]);
}
counter++;
}else{
hasNext = false;
}
}
};
reader.readAsText(files[0]);
}
</script>
</body>
</html>
Result:
element #0:
20191015
20190926
Winter Vacation
Winter vacation
element #1:
20190917
20190930
Dashain Vacation
--some-data--
element #2:
--some-data--
--some-data--
--some-data--
--some-data--
So, eg. this way its possible :)

Related

Delete element from array when deleting record from localStorage

I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.

Remove a specific item from localstorage with js

I am adding simple records to localstorage but I am having a hard time removing a specific item from my localstorage object. I am able to maintain the data on refresh and continue adding records no problem. I would like to add a button next to each entry that allows me to remove THAT particular record from localstorage and from my list.
How would I accomplish this given the code below?
var theLIst = document.getElementById('list');
var resetNotify = document.getElementById('reset-message');
var recordCounter = document.getElementById('record-counter');
var st = window.localStorage;
var count = st.clickcount;
var nameArray = [];
var newArr;
// Set the counter on refresh
if (JSON.parse(st.getItem('names'))) {
recordCounter.innerHTML = (count = JSON.parse(st.getItem('names')).length);
theLIst.innerHTML = st.getItem('names').replace(/[\[\\\],"]+/g, '');
} else {
recordCounter.innerHTML = (count = 0);
}
function addNameRecord() {
resetNotify.innerHTML = '';
var name = document.getElementById('names-field');
nameArray = JSON.parse(st.getItem('names'));
count = Number(count) + 1;
newArr = makeArr(nameArray);
// Check if there is anything in the name array.
if (nameArray != null) {
nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
} else {
nameArray = [];
nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
}
st.setItem("names", JSON.stringify(nameArray));
name.value = '';
if (!newArr[0]) {
count = 1;
theLIst.innerHTML = nameArray;
recordCounter.innerHTML = count;
} else {
theLIst.innerHTML = newArr[0].join('');
recordCounter.innerHTML = count;
}
}
// Take our string from local storage and turn it into an array we can use
function makeArr() {
return Array.from(arguments);
}
// Purge all entries, reset counter
function clearArray() {
st.clear();
nameArray = [];
theLIst.innerHTML = '';
recordCounter.innerHTML = (count = 0);
resetNotify.innerHTML = 'Array has been purged.';
}
Heres the code I tried
// Delete a specific entry
function clearThisItem(item) {
console.log(item);
localStorage.removeItem(item);
console.log(localStorage.removeItem(item))
return item;
}
Here is refactored code.
Firstly there is no need to store count, as we always have access to names.length
Store only names on localStorage, not entire HTML
For add and remove a name, fetch names array from localStorage, update it and save it back to localStorage.
After every action just update the UI using a single function call.
Note: Renamed names-field to name-field in the below implementation.
Here is the working code: https://jsbin.com/simitumadu/1/edit?html,js,output
var $list = document.getElementById('list');
var $resetMessage = document.getElementById('reset-message');
var $resetCouter = document.getElementById('record-counter');
var names = getNames();
if(names == null){
setNames([]); // initializing the empty array for first time.
}
renderData(); // display data
function addNameRecord() {
$resetMessage.innerHTML = '';
var name = document.getElementById('name-field');
addName(name.value);
renderData();
name.value = ''; //clear input field
}
function renderData(){
var names = getNames();
$resetCouter.innerText = names.length; // Count
var namesListHTML = '';
names.forEach(function(name, index){
namesListHTML = namesListHTML + '<p class="name-entry"><strong>' + (index + 1) + '. </strong> ' + name + '</p><button onclick="clearThisItem(\'' + name + '\')">Remove</button>'
});
$list.innerHTML = namesListHTML;
}
function clearArray() {
setNames([]); // clear names
$resetMessage.innerHTML = 'Array has been purged.';
renderData();
}
function clearThisItem(name){
removeName(name); // remove from localStorage
renderData();
}
function getNames(){
namesStr = localStorage.getItem('names');
if(namesStr) {
return JSON.parse(namesStr);
}
return null;
}
function setNames(names){
return localStorage.setItem('names', JSON.stringify(names));
}
function addName(name){
var names = getNames();
names.push(name);
setNames(names);
}
function removeName(name){
var names = getNames();
var index = names.indexOf(name);
if (index > -1) {
names.splice(index, 1);
}
setNames(names);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p>Count : <span id="record-counter"></div></p>
<input id="name-field">
<button onclick="addNameRecord()">Add</button>
<button onclick="clearArray()">Clear</button>
<div id="list"></div>
<div id="reset-message"></div>
</body>
</html>
Use localStorage.removeItem(insertYourKeyHere); to remove an object from local storage.
For removing it from your nameArray you can search through your list for the record, set null and then sort your list by ensuring to move objects into new positions such that null is at the end, then decrement your count for the number of records

Rerender text with updated value in fabric js

I'm using fabricjs and want to render the text every time a value is updated.
But when I do this, the new text overlaps the old. I tried to clear the object but didn't find any way to do so.
Below is the code snippet to describe what I doing:
//console.log('topp'+ rect.getTop());
rect.on('moving', function() {
var rectTop = rect.getTop();
var upCounter = 0;
var downCounter = 0;
var text40;
var canvas_objects = canvasForRect._objects;
// console.log('topp'+ rect.getTop());
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('heatMapClickData');
// CONVERT STRING TO REGULAR JS OBJECT
var text40;
var last = canvas_objects[canvas_objects.length - 1];
var parsedObject = JSON.parse(retrievedObject);
$.each(parsedObject, function(index, item) {
if (rectTop >= item['pos_y']) {
upCounter += 1;
} else {
downCounter += 1;
}
text40 = new fabric.Text("Total clicks above line" + upCounter, {
fontSize: 40
});
});
// var obj = canvasForRect.getActiveObject();
// console.log(obj);
text40.set({
text: "Total clicks above line" + upCounter
});
canvasForRect.add(text40);
// canvas.renderAll();
});
How do I re-render the text every time upCounter is updated?

Update JSON values with associated key

I am trying to collect the unique json data, I mean if the key exists the update its value. But not succeed to update the value of existing key.
var fpr_data = [{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"},
{"rfr_id":"9","user_id":"5","fp_id":"10","raw_id":"4","raw_qty":"500.00","raw_wastage":"0","raw_name":"Yarn"},
{"rfr_id":"8","user_id":"5","fp_id":"10","raw_id":"5","raw_qty":"2.00","raw_wastage":"1","raw_name":"Needle"},
{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"}];
var qty = 2, coll={}, _qty=0.00,_wastage=0.00;
// Filter and modify JSON data
$.each(fpr_data, function(i, data) {
_qty = data.raw_qty * qty;
_wastage = data.raw_wastage * qty;
// Next time add on existing keys
if( coll[data.raw_id] == data.raw_id ) {
var q = coll[data.raw_id].qty + _qty;
var w = coll[data.raw_id].wastage + _wastage;
coll[data.raw_id] = {"qty":q, "wastage":w};
}
else {
coll[data.raw_id] = {"qty":_qty, "wastage":_wastage};
}
});
console.log(coll);
In fpr_data there is raw_id that i want to collect unique ids and if the raw_id found in object then update its qty and wastage with raw_qty and raw_wastage. I got Unique JSON data but quantity and wastage are not getting update. What wrong i have done? You can find the same codes in fiddle and check the result in console.
Expected: The value of qty in 3 should be 80
JSFIDDLE
Below condition will not give you correct comparison, when object already exists in array.
if( coll[data.raw_id] == data.raw_id ) {
I think you should just do:
if(coll[data.raw_id]) {
If I understand you correctly try this example
if(coll[data.raw_id]) {
var q = coll[data.raw_id].qty + _qty;
var w = coll[data.raw_id].wastage + _wastage;
coll[data.raw_id] = {"qty":q, "wastage":w};
}
else {
coll[data.raw_id] = {"qty":_qty, "wastage":_wastage};
}
You use jQuery, so enjoy the jQuery.extend() function :
var fpr_data = [{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"},{"rfr_id":"9","user_id":"5","fp_id":"10","raw_id":"4","raw_qty":"500.00","raw_wastage":"0","raw_name":"Yarn"},{"rfr_id":"8","user_id":"5","fp_id":"10","raw_id":"5","raw_qty":"2.00","raw_wastage":"1","raw_name":"Needle"}, {"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"}];
console.log(fpr_data);
var qty = 2, coll={}, _qty=0.00,_wastage=0.00;
// Filter and modify JSON data
$.each(fpr_data, function(i, data) {
_qty = data.raw_qty * qty;
_wastage = data.raw_wastage * qty;
// Next time add on existing keys
var currentObj = coll[data.raw_id]; // Try not to repeat yourself ;-)
if( currentObj == data.raw_id ) {
var q = currentObj.qty + _qty;
var w = currentObj.wastage + _wastage;
console.log(data);
coll[data.raw_id] = $.extend(data, {"qty":q, "wastage":w});
}
else {
coll[data.raw_id] = $.extend(data, {"qty":_qty, "wastage":_wastage});
}
});
console.log(coll);
I hope this is what you were looking for.

JSON: loop Invoice Items : add if InvoiceNo not exits, update value if it does, example included

I'm trying to loop through a list of Invoices, and their Individual LineItem Values,
and in the end have an Ojbect of [object Arrays] with an Invoice Number and the total value for all line items per Invoice.
var objInvoiceLineItem = function (strInvoiceNo,strValue) {
this.InvoiceNo= strInvoiceNo;
this.Value = strValue;
}
//
var objAllInvoices = [];
//
function AddValueTo_objAllInvoices(myInvoice){
//don't know how to look and see if the Invoice exists?
//jQuery.inArray?
//for (var i = 0; i < objAllInvoices.length - 1; i++)?
if exists (myInvoice.InvoiceNo) = false{
var newObjInvoiceItem=
new objInvoiceLineItem(myInvoice.InvoiceNo, myInvoice.Value);
objAllInvoices.push(newObjInvoiceItem)
}
else{
//need help here please
var obj = getobject;
objAllInvoices.obj.Value += myInvoice.Value;
}
}
//
var Invoice1A = new objInvoiceLineItem("Invoice1",20);
var Invoice1B = new objInvoiceLineItem("Invoice1",50);
var Invoice2A = new objInvoiceLineItem("Invoice2",30);
AddValueTo_objAllInvoices(Invoice1A);
AddValueTo_objAllInvoices(Invoice1B);
AddValueTo_objAllInvoices(Invoice2A);
I think something like this will do what you want:
function AddValueTo_objAllInvoices(myInvoice)
{
for (var i = 0; i < objAllInvoices.length; i++)
{
if (objAllInvoices[i].InvoiceNo == myInvoice.InvoiceNo)
{
// invoice exists, update it and return
objAllInvoices[i].Value += myInvoice.Value;
return;
}
}
// if the invoice already existed, we would have returned in the loop
// so we wouldn't have ever gotten here, so the invoice must not exist.
// create it now:
var newObjInvoiceItem = new objInvoiceLineItem(myInvoice.Container, myInvoice.Value);
objAllInvoices.push(newObjInvoiceItem);
}

Categories