Add JSON data to an array in JavaScript - javascript

Hello I am new to JavaScript and I have been trying to parse JSON data into a JavaScript array. I can load the local .json file and print it to the console. I want to print each 'key' and 'value' pair. Having come from a python background, this is new to me. This is a sample JSON data. The structure of the data I want to use is the same. I am mostly having trouble because of the strucure of the JSON data. I have to control to change the structure of the JSON data
{
"emp_details":[
{
"emp_name":["abc"],
"email":["abc#email.com"],
"job_profile":["Full time"]
}
]
}
And here is what I have done. Which is just read the local file and print it to the console.
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
readTextFile("./data.json",function(text){
var data = JSON.parse(text);
var dataArray = []
dataArray.push(data)
//alert(data);
console.log(dataArray[0]);
});
Ideally I want the result to be like to display in an HTML table:
emp_name
email
job_profile
abc
abc#email.com
Full time
Thank you!

I am assuming that you already have defined HTML table named emp_table, so in that case, you can get desired output by following code: -
const empTable = document.getElementById('emp_table');
empTable.innerHTML = json.emp_details.map((emp) =>
Object.keys(emp).map(
(key) =>
`<tr><td><label><strong>${key}</strong><label></td><td>${emp[key][0]}</td></tr>`
)
);

You can use console.table to print tabular data.
let data = {
"emp_details": [
{
"emp_name": ["abc"],
"email": ["abc#email.com"],
"job_profile": ["Full time"]
},
{
"emp_name": ["def"],
"email": ["def#email.com"],
"job_profile": ["Full time"]
}
]
}
// convert the array in each property to a string
let emp_details = data["emp_details"].map(function(employee) {
return {
emp_name: employee.emp_name[0],
email: employee.email[0],
job_profile: employee.job_profile[0],
}
});
// print the data in a table
console.table(emp_details)

You could create a table in your html file with an id of table:
<table id="table"></table>
And then use a nested for loop to iterate through the data by doing something like this:
readTextFile("./data.json", function(text) {
var data = JSON.parse(text);
var dataArray = data.emp_details;
var table = document.getElementById("table");
for (var i = 0; i < dataArray.length; i++) {
var row = table.insertRow();
for (var key in dataArray[i]) {
var cell1 = row.insertCell();
var cell2 = row.insertCell();
cell1.innerHTML = key;
cell2.innerHTML = dataArray[i][key];
}
}
});
The first for loop iterates through the emp_details array, and the second for loop iterates through each object in the array.
The key and value of each object is then inserted into a new row in the table, with the key in the first cell and the value in the second cell.

Related

Combine a base URL and append an ID to the end by each element in multiple arrays

Forgive me, I have not used JavaScript in 10 years and I want to include any details to help me better understand.
I want to fetch data from an external API using Google Scripts into Google Sheets. Instead of fetching all data, I want to only fetch the data that I have defined in an array.
I'm attempting to join a base URL and add an ID for the data I want specifically.
I have the base URL, and a undefined end of the URL:
const urlBase = 'https://website/item?q';
var urlEnd = '';
I've tried to use join(\'=\') for each element of an array.
The Array looks something like this: (I wanted to output it in different sections when I'm fetching the data)
const itemData0 = ['1da94960-5a14-4cb0-bc25-23a07ecbc915','7ecda500-745e-4275-8b4e-b883b0a28139']
const itemData1 = ['60769d56-6fe0-464f-9d6c-d2a1b6ca6e18','a53b9b6e-3671-43fe-9429-08224083bb11']
const priceData0 = ['0080307d-3596-440c-be38-bdded3cbf4cf','5ac84494-465a-424a-b36e-fe22869ba5ec']
...
The URL should end up being: https://website/item?q=1da94960-5a14-4cb0-bc25-23a07ecbc915
Which should give me,
Header: Items 0
Row0: Data1, Data1a (Each Url ID)
...
Header: Items 1
Row0: Data1, Data1a
...
The API endpoint: (Adding, the let i=o; i<array.length; i++ for each array to replace url)
And collecting Data:
function getItemData() {
let urlData = [];
for (let i=0; i<urlEnd.length; i++) {
urlData[i] = [];
urlData[i][0] = urlEnd[i].itemData0;
urlData[i][1] = urlEnd[i].itemData1;
urlData[i][2] = urlEnd[i].priceData0;
urlEnd.forEach("join function")
}
let data = fetchJSON('https://website/item?q=' + urlData);
let range = ssPrivateData.getRange(`A${1 + HEADER_ROWS_COUNT}:E${1 + HEADER_ROWS_COUNT + data.length - 1}`);
let sheetData = [];
for (let i=0; i<data.length; i++) {
sheetData[i] = [];
sheetData[i][0] = data[i].id;
sheetData[i][1] = data[i].name;
sheetData[i][2] = data[i].price;
sheetData[i][3] = data[i].date;
sheetData[i][4] = data[i].lastSale;
}
range.setValues(sheetData);
setLastUpdateDate();
}
function fetchJSON(url) {
try {
var response = UrlFetchApp.fetch(url, { headers: { 'x-api-key': API_KEY }});
var json = response.getContentText();
var data = JSON.parse(json);
return data;
}
catch(err) {
status = err.message;
}
return status;
}
I cannot get the URLs to combine for each of the arrays. I've tried running this script offline to pull random data to test formatting, but I cannot even get the data to input.
UPDATE
What I did was take all the data instead of the specific ID's. and then filtered the the data that wasn't equal to the array defined. Look at one of the answers, I've explained what I did differently.
Sorry the question wasn't easily understood. hopefully my answer below clarifies what I was trying to do. I still don't know how to append a URL and add ID to it. I feel filtering is better as I dont have to query each time for each ID there is. I just do it once, and ignore the id's I don't want.
I filtered the total results instead of appending each ID to a url.
var filtered_items = {
item_data1 : [array 1],
item_data2 : [array 2]
};
let sheetData = [ ['header 1', 'header 2']];
var row_data = [];
for(var set_key in filtered_items) {
row_data = [ set_key, '', '','', '','',];
sheetData.push(row_data);
for (var k in filtered_items[set_key][k] {
for (let i=0; i<data.length; i++) {
if (data[i].id == filtered_items[set_key][k]) {
row_data = [
set_key,
sheetData[i].id;
sheetData[i].name;
sheetData[i].price;
sheetData[i].date;
sheetData[i].lastSale;
];
sheetData.push(row_data);
break;
}
}
}
row_data = ['','','', '','',];
sheetData.push(row_data);
}
....

read cells content of dataobject

I read a csv file using javascript code and i want to push it into a a 2D Array in order to do some processing
var dataArray = new Array;
function parseCSV(dataArray) {
//replace UNIX new lines
data = data.replace(/\r\n/g, "\n");
//replace MAC new lines
data = data.replace(/\r/g, "\n");
//split into rows
var rows = data.split("\n");
// loop through all rows
for (var i = 0; i < rows.length; i++) {
// this line helps to skip empty rows
if (rows[i]) {
// our columns are separated by comma
var column = rows[i].split(",");
var date=column[0];
var value = column[4];
// create object which contains all these items:
var dataObject = {
date: date,
T4: value
};
dataArray.push(dataObject);
}
}
}
}
As a test, i try to read a cell content and display on the web page to verify that i read the file.
<script type="text/javascript">
var x= dataArray[1][4];
document.write(x);
</script>
but it doesn't show anything.
Can anyone Help??
var dataArray = new Array;
var data = "Date,Description,Created By,Modified By,T4 Tag\n";
data += "20170424,This is record 1,user1,none,Just work please.\n";
data += "20170424,This is record 2,user2,none,I'm trying too.\n";
function parseCSV(dataArray) {
//replace UNIX new lines
data = data.replace(/\r\n/g, "\n");
//replace MAC new lines
data = data.replace(/\r/g, "\n");
//split into rows
var rows = data.split("\n");
// loop through all rows
for (var i = 0; i < rows.length; i++) {
// this line helps to skip empty rows
if (rows[i]) {
// our columns are separated by comma
var column = rows[i].split(",");
var date=column[0];
var value = column[4];
// create object which contains all these items:
var dataObject = {
date: date,
T4: value
};
dataArray.push(dataObject);
}
}
}
parseCSV(dataArray);
Lacking a file, I forced some CSV data into a string for processing.
Your question is not showing these two items:
how you are setting var data
how you are calling parseCSV(dataArray)
If these two things are present all should work - Here's the proof
As far as the html script portion:
your array addressing looks wrong - it seems like it should look like:
<script>
var x = dataArray[1].T4;
document.write(x);
</script>
Here's my reasoning:
I understand that you are passing the CSV data to this function for parsing it into your dataArray variable - correct?
If correct, this data will look something like I have added manually (I added this directly just to work with something).
The bigger item is not so much where the data is coming from, but that ultimately it gets parsed by this parseCSV function.
When this happens, you are building appending to the empty dataArray variable in the following way:
For the first pass this will look as follows:
[{"date" : "Date", "T4" : "T4 Tag"}]
For the second pass:
[{"date" : "Date", "T4" : "T4 Tag"}, {"date" : "20170424", "T4" : "Just work please."}]
For the third pass:
[{"date" : "Date", "T4" : "T4 Tag"}, {"date" : "20170424", "T4" : "Just work please."}, {"date" : "20170424", "T4" : "I\'m trying too."}]
So now when you are in your html section of code, you have no key of address [4].
Your code says:
var x = dataArray[1][4];
Consider the following to see what I mean:
var record = dataArray[1];
//{"date" : "20170424", "T4" : "Just work please."}
//There is no key 4 here only date & T4.
var date = record.date;//returns: "20170424"
var t4 = record.T4;//returns: "Just work please."
In Contrast if you had the following - your method would work
myObj = {"date" : "20170424", "4" : "This is a value for field 4", "T4" : "Just work please."}
myObj[4];//returns "This is a value for field 4";
hopefully this explains it clearly enough.
here is the load csv file function
function loadCSV(file) {
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load
request.open('GET', file, false);
request.send();
parseCSV(dataArray);
}

Working with Localstorage for put content in table (JQuery)

I have a big problem working with this.
I have a table in my html, in my js I'm using localstore (I have never used that before)
I insert a new row, and it is stored with localstore, I create a JSON.
For putting the ID of the raw, I just get the length of my localstorage.
For example, I have 3 rows, with IDs 1, 2 and 3.
If I decide to delete one, we can say the number 2, I can delete it, yeah, but the next time when I create a new raw I'll have the id = 2.
why?, because I use localstorage.length+1 for putting the id, so... If I had 3 before, the next time I'll get a 3, I'll replace my content where ID = 3.
what can I do for avoid that mistake?
my JS is this
crearTabla(tablastorage)
$("#btnNuevo").on('click',function(){
$("#mymodal1").modal("show");
$('#btnGuardar').data('evento','crear');
});
$("#btnCargar").on('click',function(){
crearTabla(tablastorage)
});
$("#btnGuardar").on('click',function(){
if($(this).data('evento') == "crear"){
Crear();
$('input:text').val('');
}
else{
Modificar();
}
$("#mymodal1").modal("hide");
});
function crearTabla(data){
$("#tabla").empty();
$.each(data, function(index, val){
var temp = JSON.parse(val);
var $tr = $("<tr/>");
var $tdID = crearTD(temp.id);
var $tdMatricula = crearTD(temp.matricula);
var $tdNombre = crearTD(temp.nombre);
var $tdSexo = crearTD(temp.sexo);
var $tdAccion = crearAccion(temp);
$tr.append($tdID, $tdMatricula, $tdNombre, $tdSexo, $tdAccion);
$("#tabla").append($tr);
$('input:text').val('');
})
}
function Crear(){
var $tr = $("<tr/>");
var $tdID = crearTD(tablastorage.length+1);
var $tdMatricula = crearTD($("#matricula").val());
var $tdNombre = crearTD($("#nombre").val());
var $tdSexo = crearTD($("#sexo").val());
var JSon = {
id:tablastorage.length+1,
matricula:$("#matricula").val(),
nombre:$("#nombre").val(),
sexo:$("#sexo ").val()
}
if($('#matricula').val()=='' || $('#nombre').val()=='' || $('#sexo').val()==''){
alert("Uno o mas campos vacios");
}
else{
tablastorage.setItem(tablastorage.length, JSON.stringify(JSon))
var $tdAccion = crearAccion(JSon);
crearTabla(tablastorage)
$('input:text').val('');
}
};
function crearTD(texto){
return $("<td/>").text(texto);
};
function crearAccion(objeto){
var $td = $("<td/>");
var $div = $("<div/>",{
class:'btn-group',
role:'group'
});
var $btnElminar = $("<button/>",{
class:'btn btn-danger eliminar'
}).html("<i class='glyphicon glyphicon-remove'></i>"
).data('elemento',objeto);
var $btnModificar = $("<button/>",{
class:'btn btn-info modificar'
}).html("<i class='glyphicon glyphicon-pencil'></i>"
).data('elemento',objeto);
$div.append($btnElminar, $btnModificar)
return $td.append($div);
};
$("#tabla").on('click','.eliminar',function(event){
console.log($(this).data('elemento').id)
tablastorage.removeItem($(this).data('elemento').id-1)
crearTabla(tablastorage)
});
$("#tabla").on('click','.modificar',function(event){
index = $(this).data('elemento').id-1;
var $elemento = $(this).data('elemento');
$('#btnGuardar').data('evento','modificar');
$('#id').val($elemento.id);
$('#matricula').val($elemento.matricula);
$('#nombre').val($elemento.nombre);
$('#sexo').val($elemento.sexo);
$("#mymodal1").modal("show");
});
and my html have this code:
http://notes.io/wAYL
Two extra things.
1. Sorry for my bad english, If I've made a mistake is because I speak spanish, not english all the time, I need to improve my skills with the languague.
2. Also because I don't know how to put the code here. I just tried and I faild so many times.
<-- Please don't erase this -->
What i usually do is store whole arrays in one storage key as JSON.
When you load page you get whole array using something like:
var data = JSON.parse( localStorage.getItem('tableData') || "[]");
$.each(data, function(_, item){
// append html to table for each item
});
Then in your Crear() you would push the new item into the array, and store the whole array
var JSon = {
id: +new Date(),
matricula:$("#matricula").val(),
nombre:$("#nombre").val(),
sexo:$("#sexo ").val()
}
data.push(JSon);
localStorage.setItem('tableData', JSON.stringify(data));
Similar to remove an item , splice() the array to remove it from main array and store again.
One suggestion for ID is use current timestamp

How to access a text file using javascript?

I am making a jquery ajax call to the following text file:
sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End
The call is working fine. But I really don't know how to access a particular value like lets say, 'China' from the above text file? I am trying tis for the first time. please help..
Here is the parseParams plugin which you can use to split a querystring into an array.
You can use it like this:
var querystring = 'sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End';
var paramsObj = $.parseParams(querystring);
alert(paramsObj.sport); // = Table Tennis
Don't use such file structure. Use JSON instead. i.e:
{
"sport":"Table Tennis",
"groups":false,
"no_groups":"",
"grp_names":[
],
"teams":[
{
"China":6157
},
{
"Finland":6158
},
{
"Sweden":6159
},
{
"Japan":6149
},
{
"Korea":6154
}
],
"Endstr":"End"
}
Then, after you parse it with $.get or $.ajax, you just access:
data.sports
for example.
Here is code to parse your data. It would have been straight forward if you have chosen JSON as return data.
function myParser() {
var str = "sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End";
var arPairs = str.split("&");
var outObj = {};
for (var i=0; i < arPairs.length; i++) {
var arTemp = arPairs[i].split("=");
var key = arTemp[0];
var value = arTemp[1];
if (key === "teams") {
arTemp = value.split("~");
var teamObj = {};
for (var j=0; j < arTemp.length; j++) {
var arTeamData = arTemp[j].split("^");
teamObj[arTeamData[1]] = arTeamData[2];
}
value = teamObj;
}
outObj[key] = value;
}
return outObj;
}
output: Is an array having all your data available. You can refer it as:
var outObj = myParser();
console.log(outObj.sport); // Prints "Table Tennis"
console.log(outObj.teams.china) // Prints china data

Replace Element in JSON with a element in a Javascript array

I have this JSON
[{"id":7,"serial":"7bc530","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":8,"serial":"4a18d27","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":9,"serial":"f30ef","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":10,"serial":"9e6d","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":11,"serial":"4d8665a3","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":12,"serial":"4fe1457","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null}]
and I have this JSON
{"computers":[{"id":"7bc530","name":"Dell","description":"Dell"},
{"id":"f30ef","name":"HP","description":"HP"},
{"id":"9e6d","name":"Compaq","description":"Compaq"},
{"id":"4d8665a3","name":"Toshiba","description":"Toshiba"},
{"id":"4fe1457","name":"Asus","description":"Asus"},
{"id":"4a18d27","name":"Acer","description":"Acer"}]}
I want to replace the "serial" element in the first JSON with the "Description" in this one. The reason why I need it in one JSON is that I am using a DataTable and I can only pass one JSON in.
I'm not sure how I can do this in Javascript / JQuery?
You can accomplish this without any jQuery by setting up small function:
(see the demo fiddle)
function replaceSerial (data1, data2) {
var descs = {}, computers = data2['computers'], final = data1;
for (var i = 0; i < computers.length; i++ ) {
descs[computers[i]['id']] = computers[i]['description'];
}
for (var i = 0; i < data1.length; i++) {
final[i]['serial'] = descs[data1[i]['serial']];
}
return final;
}
Then just save your two pieces of JSON into variables and invoke the function:
var json1, json2, mergedJson;
json1 = // DATA IN FIRST JSON;
json2 = // DATA IN SECOND JSON;
mergedJson = replaceSerial (json1, json2);
Assuming your first object is called to and the second object is called from
// Iterate over each entry in to
to.forEach(function(value) {
// In each iteration find elements in from where the id is the same
// as the serial of the current value of to
var description = from.computers.filter(function(element){
if (element.id == value.serial) return true;
});
// Copy description of first found object in the description property of
// the current object
value.description = description[0].description;
// Unset serial?
delete value.serial;
});
DEMO

Categories