Loop fetches all the words in 1 input field - javascript

as you can see in the picture below, my words 'es' and 'presso' are put into one input field instead of 'es' in one and 'presso' in another input field.
how my JSON looks like:
{
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Example",
"language": "nl_NL",
"exercises": [
{
"word": "espresso",
"syllables": [
"es",
"presso",
"",
""
]
}
]
},
"dataType": "json"
}
}
This is how my loop looks like:
$.map(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + i).val(exercise.word) // starts with 0
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$(".syllable" + s).val(exer.syllables);
});
});
to zoom in on the loop where I fetch the syllables:
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$(".syllable" + s).val(exer.syllables);
});
the function where I create the syllable inputs:
function getWordPartInput(id, cValue){
cValue = cValue || '';
var wpInput = $('<input/>', {
'class': 'form-group form-control syllable' + SyllablesID++,
'type': 'text',
'value': cValue,
'placeholder': 'Syllables',
'name': 'Syllablescounter['+ SyllablesID++ +']'
});
return wpInput;
}
what is it that I am doing wrong? (I did declare the variable SyllablesID so don't worry about that part).

var data = {
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Example",
"language": "nl_NL",
"exercises": [
{
"word": "espresso",
"syllables": [
"es",
"presso",
"",
""
]
}
]
},
"dataType": "json"
}
};
function draw(data){
for (ex of data.main_object.main_object.exercises){
for( sy of ex.syllables){
$("#container").append(`<input type="text" value="${sy}">`)
}
}
}
draw(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container"><div>
syllables is an array as per to posted JSON so you'll have to get each value and add it as a value to the input element. You can again use .map or for/forEach etc to loop through syllabus array and add the array entries to input values
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$.map(exer.syllables, function(syll, i){
$(".syllable" + i).val(syll);
})
});

Related

How do I access lower level variables and concat them when importing with ajax

I am looking at the following json file:
"data": [
{
"Date": "2021-01-29",
"Rating": 1018.81,
"League_points": "TBD",
"Team": {
"Team": "Columbus Blue Jackets",
"modification": "+-diff",
"Logo": "<img src='img/NHLpics/columbusBlueJackets.gif' style='height:40%; width:40%'>"
},
"Division": "Metropolitan",
"President's Trophy": "TBD",
"Playoff Qualifier": "TBD",
"Conference Winner": "TBD",
"Stanley Cup": "TBD"
},
{
"Date": "2021-01-29",
"Rating": 976.12,
"League_points": "TBD",
"Team": {
"Team": "Chicago Blackhawks",
"modification": "+-diff",
"Logo": "<img src='img/NHLpics/chicagoBlackhawks.gif' style='height:40%; width:40%'>"
},
"Division": "Central",
"President's Trophy": "TBD",
"Playoff Qualifier": "TBD",
"Conference Winner": "TBD",
"Stanley Cup": "TBD"
},
and trying to import it into an HTML table with the following function :
function getStandings(){
var date = document.getElementById("standingsDate");
var path = "data/NHL/DataForNHL_" + date.value + ".json";
$(document).ready(function() {
var table = $('#example').DataTable( {
paging: false,
destroy: true,
"ajax": path,
"columns": [
{ "data": "Rating" },
{ "data": "League_points" },
{ "data": "Team.Logo"},
{ "data": "Division" },
{ "data": "President's Trophy" },
{ "data": "Playoff Qualifier" },
{ "data": "Conference Winner" },
{ "data": "Stanley Cup" }
]
} );
setTimeout(myFunction, 100)
obj = document.getElementById("example_filter");
obj.remove();
} );
}
The problem I am facing, is that instead of importing just Team.Logo, I would like to import it so that it displays Team.Logo, Team.modification and Team.Team in the same table cell of the column. Can anyone show me if this is possible?
Please let me know if more information is needed, thanks in advance!
Instead of this:
{ "data": "Team.Logo"},
Use this:
{
"data": "Team",
"render": function ( data, type, row ) {
//console.log( data )
return data.Logo + ' ' + data.Team + ' ' + data.modification;
}
},
This renders a cell as:
<td>
<img src="img/NHLpics/chicagoBlackhawks.gif" style="height:40%; width:40%"> Chicago Blackhawks +-diff
</td>
Of course, you may wish to change the layout from the one I have used.
You can see some more column renderer examples here: columns.render().
Specifically, in the "Transforming data" example, look at render: function ( data, type, row ) { ... }.
More detailed syntax documentation can also be found here.

Deleting a key in JSON while making ajax call from javascript

I am new to java script and ajax. I have a JSON and I want to remove outputs cell in this JSON:
{
"cells": [{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "print(\"hi\")",
"execution_count": 1,
"outputs": [{
"output_type": "stream",
"text": "hi\n",
"name": "stdout"
}]
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"name": "Python [Root]",
"display_name": "Python [Root]",
"language": "python"
},
"anaconda-cloud": {},
"language_info": {
"pygments_lexer": "ipython3",
"version": "3.5.0",
"codemirror_mode": {
"version": 3,
"name": "ipython"
},
"mimetype": "text/x-python",
"file_extension": ".py",
"name": "python",
"nbconvert_exporter": "python"
},
"gist": {
"id": "",
"data": {
"description": "Untitled5.ipynb",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
and this is my attempt on removing the outputs cell. This piece of code posts the data to above mentioned JSON:
"use strict";
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
var outputs = data.cells;
var data_dup = _objectWithoutProperties(data, ["outputs"]);
var id_input = $('#gist_id');
var id = params.gist_it_personal_access_token !== '' ? id_input.val() : '';
var method = id ? 'PATCH' : 'POST';
// Create/edit the Gist
$.ajax({
url: 'https://api.github.com/gists' + (id ? '/' + id : ''),
type: method,
dataType: 'json',
data: JSON.stringify(data_dup),
beforeSend: add_auth_token,
success: gist_success,
error: gist_error,
complete: complete_callback
});
};
But this code doesnt work. Can some one please guide how can we directly strip a key(outputs in this case) from ajax call and post it to JSON.
This is a gist extension of jupyter notebook and I am trying to strip output while posting it to gist on github
function _objectWithoutProperties(obj, key="outputs") { obj.cells.forEach(cell=>delete(cell[key])); }
If you use ES6, you can use this syntax to remove outputs:
{
...data,
cells: data.cells.map(({ outputs, ...otherProps }) => otherProps),
}
Note: data is your complete object.

Nesting Json Data with jquery

I have this data from a csv file that i have to use in a dependant dropdown with jquery. I can't figure out if it is possible to nest the data i received for what i already have coded.
CSV file
Banco Tarjeta Cuotas Medio_Pago Coeficiente TEA CFT
Santander Visa 1 modulodepago2 1 0.00% 0.00%
Santander Visa 1 nps 1.0262 18.56% 22.84%
Frances Visa 1 modulodepago2 1 0.00% 0.00%
Frances Master 2 nps 1.0262 18.56% 22.84%
My json data comes like this
[{"banco":"Santander","tarjeta":"Visa","cuotas":"1","medio_pago":"modulodepago2",
"coeficiente":"1","tea":"0.00%","cft":"0.00%"},
{"banco":"Santander","tarjeta":"Visa","cuotas":"1","medio_pago":"nps",
"coeficiente":"1.0262","tea":"18.56%","cft":"22.84%"} ...
etc...
Is there a way i can nest this json data like this (+ adding unique names and id's)?
var myJson = {
"banco": [
{
"name": "Santander",
"id": "Santander",
"tarjeta": [
{
"name": "Visa",
"id": "SantanderVisa",
"cuotas": [
{
"name": "1",
"id": "SantanderVisa1",
"medio_pago": "modulodepago2"
"coeficiente": "1",
"tea": "0.00%",
"cft": "0.00%",
},
{
"name": "1",
"id": "SantanderVisa2",
"medio_pago": "nps"
"coeficiente": "1.0262",
"tea": "18.56%",
"cft": "22.84%",
}
]
}
]
},
{
"name": "Frances",
"id": "Frances",
"tarjeta": [
{
"name": "Visa",
"id": "FrancesVisa",
"cuotas": [
{
"name": "1",
"id": "FrancesVisa1",
"medio_pago": "modulodepago2"
"coeficiente": "1",
"tea": "0.00%",
"cft": "0.00%",
}
]
},
{
"name": "Master",
"id": "FrancesMaster",
"cuotas": [
{
"name": "2",
"id": "FrancesMaster2",
"medio_pago": "nps"
"coeficiente": "1.0262",
"tea": "18.56%",
"cft": "22.84%",
}
]
}
]
}
]
}
You will need to group by keys. An easy way to do this is to use Lodash or Underscore.js.
I used Papa Parse to convert the CSV data into JSON.
var csvData = $('#csv-data').text().trim();
var jsonData = Papa.parse(csvData, { delimiter:',', header:true }).data;
var transformedJson = {
banco : _.chain(jsonData)
.groupBy('Banco')
.toPairs()
.map(banco => {
return {
name : banco[0],
id: banco[0],
tarjeta : _.chain(banco[1])
.groupBy('Tarjeta')
.toPairs()
.map(tarjeta => {
return {
name: tarjeta[0],
id: banco[0] + tarjeta[0],
cuotas: _.map(tarjeta[1], cuota => {
return {
name: cuota['Cuotas'],
id: banco[0] + tarjeta[0] + cuota['Cuotas'],
medio_pago: cuota['Medio_Pago'],
coeficiente: cuota['Coeficiente'],
tea: cuota['TEA'],
cft: cuota['CFT']
}
})
};
})
}
}).value()
}
console.log(JSON.stringify(transformedJson, null, 2));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.4/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<textarea id="csv-data" style="display:none" rows="5" cols="72">
Banco,Tarjeta,Cuotas,Medio_Pago,Coeficiente,TEA,CFT
Santander,Visa,1,modulodepago2,1,0.00%,0.00%
Santander,Visa,1,nps,1.0262,18.56%,22.84%
Frances,Visa,1,modulodepago2,1,0.00%,0.00%
Frances,Master,2,nps,1.0262,18.56%,22.84%
</textarea>
try something like this
you get all medio_pago for the others objects you just use the object name.
I haven't tested it but I'm sure this will work for you.
var Json = ...
$.each(Json, function(i, item) {
alert(myJson[i].banco.tarjeta.cuotas.medio_pago);
});

D3.js node color based on type

Given the below json structure:
{
"nodes": [
{
"type": "school",
"country": "US",
"name": "saint peter's",
"id": 1006
},
{
"type": "univeristy",
"country": "Brazil",
"name": "saint joseph's",
"id": 1007
}
...
],
"links": [
{
"source": 1006,
"target": 1007,
"value": 20
},
],
"types": [
{
"type": "school",
"image": "image01"
},
{
"type": "univeristy",
"image": "image02"
},
{
"type": "company",
"image": "image03"
},
]
}
I get the list of the type of nodes from types.type and append it to a html tag; assigning a color to each list item. When I change the color in the color picker container, in any of the list items, it only changes the color for .school , because it is hardcoded in here MyNode = d3.select("#node").selectAll(".school").select("circle");
how can I change it to match the type in the list item with the node type found in the nodes.type?
$(document).ready(function () {
$.getJSON("data.json", function (obj) {
$('#filterColor').data('types', obj.types.map(function (o) {
// console.log(o.type);
return o.type;
})).append(obj.types.map(function (o) {
return '<li>' + o.type + '<input class="color-picker" type="text"/></li>';
}).join(''));
$("#filterColor .color-picker").each(function(){
$(this).spectrum({
color: (function (m, s, c) {
return (c ? arguments.callee(m, s, c - 1) : '#') +
s[m.floor(m.random() * s.length)]
})(Math, '0123456789ABCDEF', 5),
preferredFormat: "rgb",
showInput: true,
showPalette: true,
showAlpha: true,
palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]],
change: function(color) {
MyNode = d3.select("#node").selectAll(".school").select("circle");
MyNode.style("fill", function(d) { return d3.rgb(color.toHexString()) });
ColorSchool = d3.rgb(color.toHexString());
}
});
});
});
});
which passes into this function:
function ColorType(d)
{
if (d.type == "school") { return ColorSchool;}
if (d.type == "univeristy"){ return Coloruniveristy;}
if (d.type == "company"){ return Colorcompany;}
}
You could store the type reference in the actual element, in a custom attribute. Since it's only one string you need, this might be enough to fix your problem.
When creating the <li> element, you add an attribute, e.g.: data-fortype, with the o.type string.
In the each that initializes the spectrum thingy, you extract it using this.getAttribute or the jQuery equivalent.
An example, in vanilla js: (I don't really know the jQuery API, sorry about that)
var data = {
"types": [{
"type": "school",
"image": "image01"
}, {
"type": "univeristy",
"image": "image02"
}, {
"type": "company",
"image": "image03"
}]
};
// Make UI from code:
makeUI();
function makeLi(type) {
return "<li>" +
type.type +
// (1) Here, the selector is stored in attr.
"<input class='test' data-forType='" +
type.type +
"' type='text' /></li>"
};
function onChange(e) {
// (2) Here, we retreive the attribute
console.log("Selector: " + e.target.getAttribute("data-forType"));
};
function makeUI() {
data.types.forEach(function(type) {
document.querySelector("ul").innerHTML += makeLi(type);
});
Array.from(document.querySelectorAll("li"))
.forEach(function(el) {
el.addEventListener("change", onChange);
});
};
<ul>
</ul>

Dynamic table from JSON using javascript

I use the following json to develop a table structure. But I'm unable to go ahead on adding rows according to columns.
[
{
"authType": "BasicAuth",
"phases": [
{
"type": "Development",
"keys":[{
"username": "developer"
},{
"password": "password123"
}]
},
{
"type": "Testing",
"keys":[{
"username": "tester"
},{
"password": "password123"
}]
}
]
},
{
"authType": "AccessToken",
"phases": [
{
"type": "Development",
"keys":[{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/developer"
}]
},
{
"type": "Testing",
"keys":[{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/testing"
}]
}
]
},
{
"authType": "OAuth",
"phases": [
{
"type": "Development",
"keys":[{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/development"
}]
},
{
"type": "Testing",
"keys":[{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/testing"
}]
}
]
}
]
I use the following script to iterate over the json.
var subTable = '<div class="subtable"><table data-clicked-parent-row="'+ clickedCell.row
+'" data-clicked-column="'+ clickedCell.column +'"><tr><th>Keys</th>';
tableData.forEach(function(e){
if(rowType == e.authType){
var phases;
e.phases.forEach(function(t){
subTable += '<th>'+ t.type +'</th>'
})
return subTable + '</tr></table></div>';
}
})
The thing is, I'm unable to add rows to the table while iterating on the objects. The following is a static version of the table. how can i write a generic function to achive the following table structure. Please let me know any better way to write the iteration.
var data = {
"Items": [
{
"id": "A004"
, "name": "ACC LR2"
, "userId": ["1","2","3","4"]
}, {
"id": "0001"
, "name": "ABG IT"
, "userId": ["8","9","10","11"]
}
]
}
function getUserId(obj){
result = []
obj.Items.forEach( function(item, i){
result.push(item.userId);
});
return result;
}
function getUserIdAll(obj){
result = []
obj.Items.forEach( function(item, i){
result = result.concat(item.userId);
});
return result;
}
console.log( getUserId(data) );
console.log( getUserIdAll(data) );
var data = [
{
"authType": "BasicAuth",
"phases": [
{
"type": "Development",
"keys": [
{
"username": "developer"
},
{
"password": "password123"
}
]
},
{
"type": "Testing",
"keys": [
{
"username": "tester"
},
{
"password": "password123"
}
]
}
]
},
{
"authType": "AccessToken",
"phases": [
{
"type": "Development",
"keys": [
{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/developer"
}
]
},
{
"type": "Testing",
"keys": [
{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/testing"
}
]
}
]
},
{
"authType": "OAuth",
"phases": [
{
"type": "Development",
"keys": [
{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/development"
}
]
},
{
"type": "Testing",
"keys": [
{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/testing"
}
]
}
]
}
];
function objGetKeyVal(obj){
for (var key in obj) {
return [ key, obj[key] ];
}
}
(function createTable(tableData){
var table = '<table>';
// tableHeader += '<caption>Caption</caption>';
// Creating table header
// table += '<tr>';
// table += '<th>Keys</th>';
// table += '<th>Development</th>';
// table += '<th>Testing</th>';
// table += '</tr>';
// Sub tables iterator
tableData.forEach(function(subTable, i){
tableRows = []; // Rows array for sub table
table += '<tr><th>Keys</th>'; // Table headers creating
subTable.phases.forEach(function(colData, icol){
table += '<th>'+colData.type+'</th>'; // Creating table headers for each phases
colData.keys.forEach(function(key, irow){ // Converts structured data to array of rows arrays of columns
if( tableRows[irow] === undefined) { tableRows[irow] = []; }
rowData = objGetKeyVal(key);
tableRows[irow][0] = rowData[0];
tableRows[irow][icol+1] = rowData[1];
});
});
table += '</tr>'; // End table header cration
// Now we have usual table array - need only convert it to HTML
// table looks like: [ ['col1', 'col2', 'col3'], ['col1', 'col2', 'col3'] ]
table += '<tr><th colspan="3">'+subTable.authType+'</th></tr>';
tableRows.forEach(function(row){
table += '<tr>';
row.forEach(function(str){
table += '<td>'+str+'</td>';
});
table += '</tr>';
});
});
table += '</table>';
$('body').append(table);
})(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Use this function for render table with json. Observe this function works with simple json. For complex json necessary adapter this function
var tableData = [
{
"Name": "Kevin",
"Adress": "Adress UHE, SC",
},
{
"Name": "Jose",
"Adress": "Adress KUK, CC",
},
{
"Name": "Kevin",
"Adress": "Adress CGH, JK",
}
];
function compile(){
var subTable = '', column = '', row = '';
for(c in tableData[0])
column += '<th>' + c + '</th>';
for(item in tableData){
row += '<tr>';
for(c in tableData[0]) row += '<td>' + tableData[item][c] + '</td>';
row += '</tr>';
}
console.log(row)
return '<table border="solid 1px"><tr>' + column + '</tr>' + row + '</table>';
};
document.write(compile());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources