How to create and populate multiple tables from multidimensional array using javascript - javascript

I am trying to create and populate multiple tables from a multidimensional array. My array is a multidimensional array that looks like below:
{
"John Snow": [
{
"user_id": "4",
"id": "28",
"clock_in": "2019-06-03 14:32:14",
"clock_out": "2019-06-04 14:32:14",
"time": "24.00",
"first_name": "John",
"last_name": "Snow"
},
{
"user_id": "4",
"id": "29",
"clock_in": "2019-06-04 20:47:18",
"clock_out": "2019-06-05 18:47:18",
"time": "22.00",
"first_name": "John",
"last_name": "Snow"
}
],
"Frank Thomas": [
{
"user_id": "6",
"id": "30",
"clock_in": "2019-06-03 06:32:04",
"clock_out": "2019-06-05 14:05:04",
"time": "55.55",
"first_name": "Frank",
"last_name": "Thomas"
}
]
}
I am not sure how to loop through this with javascript, I'm guessing I will need to nest a for loop but not sure how to structure it.
I was able to loop through and populate a single table just fine when my array structure was a single array with no keys using the below code:
<div id="tables"></div>
<script type="text/javascript">
function search_data(){
var fromDate = $('#from_date').val();
var toDate = $('#to_date').val();
var userId = $('#employee_option').val();
$.ajax({
url:"<?php echo base_url(); ?>clock/search_data",
method:"post",
dataType:"JSON",
data:{fromDate:fromDate, toDate:toDate, userId:userId},
success:function(data){
console.log(data)
var html = '<table class="table table-striped table-condensed table-responsive" id="myTable"><thead><tr><th>Employee</th><th>Time In</th><th>Time Out</th><th>Total Time</th><th>Action</th></tr></thead><tbody>';
for(var count = 0; count < data.length; count++){
html += '<tr>';
html += '<td class="table_data" data-row_id="'+data[count].id+'" data-column_name="id" >'+data[count].first_name+" "+data[count].last_name+'</td>';
html += '<td><input type="text" class="dateedit" data-row_id="'+data[count].id+'" data-column_name="clock_in" value="'+data[count].clock_in+'"></td>';
html += '<td><input type="text" class="dateedit" data-row_id="'+data[count].id+'" data-column_name="clock_out" value="'+data[count].clock_out+'"></td>';
html += '<td class="table_data" data-row_id="'+data[count].id+'" data-column_name="time">'+data[count].time+'</td>';
html += '<td><button type="button" name="delete_btn" id="'+data[count].id+'" class="btn btn-xs btn-danger btn_delete"><span class="glyphicon glyphicon-trash"></span></button></td></tr>';
}
$('#tables').html(html);
$('.dateedit').each(function(){
$(this).datetimepicker({
format: "YYYY-MM-DD H:mm:ss",
sideBySide: true
});
});
}
});
}
</script>
Any help would be appreciated, hopefully this makes sense.
Here is a picture of what I have with a basic array:
Here is what I am trying to accomplish:

I would loop over the employees and pass them to another function to print out each employee... because I find nested loops hard to understand. easier to maintain & modify separate functions, IMO.
Note: I am a PHP dev who does minimal javascript, so don't expect my code to be up to snuff. I think this does what you want.
let employees = {
"John Snow": [
{
"user_id": "4",
"id": "28",
"clock_in": "2019-06-03 14:32:14",
"clock_out": "2019-06-04 14:32:14",
"time": "24.00",
"first_name": "John",
"last_name": "Snow"
},
{
"user_id": "4",
"id": "29",
"clock_in": "2019-06-04 20:47:18",
"clock_out": "2019-06-05 18:47:18",
"time": "22.00",
"first_name": "John",
"last_name": "Snow"
}
],
"Frank Thomas": [
{
"user_id": "6",
"id": "30",
"clock_in": "2019-06-03 06:32:04",
"clock_out": "2019-06-05 14:05:04",
"time": "55.55",
"first_name": "Frank",
"last_name": "Thomas"
}
]
};
function get_employee_table(employeeName, employees){
let str = "<table><tr><td>Employee Name</td><td>Clock In</td><td>Clock Out</td></tr>";
for (let index in employees[employeeName]){
let clock = employees[employeeName][index];
str +="<tr><td>"+(clock['first_name']+" "+clock['last_name'])+"</td>"
+ "<td>"+clock['clock_in']+"</td>"
+ "<td>"+clock['clock_out']+"</td>"
+ "</tr>";
}
str +="</table>";
return str;
}
for (let employee in employees){
document.getElementById("employee_table_demo").innerHTML = document.getElementById("employee_table_demo").innerHTML +
get_employee_table(employee,employees);
}
<div id="employee_table_demo"></div>
Now... here's where I share my opinion. I think you probably could have done this on your own. I had a hard time figuring out how to correctly loop over the objects, since the forin gave me the key, rather than the value. But the actual operation wasn't very complex. I realize we're all at different stages in our skill set, and if you're newer this could have seemed very perplexing. It seems like the kind of problem, though, that just required more elbow grease and maybe pushing through some frustration. T'was a nice learning experience for me though. And a good way to avoid working on my own projects lol.

Use a for..in loop to loop through the object and forEach through the array.
for(let row in data) {
data[row].forEach(cell => {
...
}
}

Related

Swap rows/indexes within a JavaScript array using AngularJS

I have a custom directive that is holding an array of JavaScript objects.
The object is a little complex and lengthy but I will display something similar to point out my problem:
A JSON.stringify of this displays the following:
[
{
"Id": 1,
"Name": "John Doe",
"EMail": "john#doe.com"
},
{
"Id": 2,
"Name": "Jim Doe",
"EMail": "jim#doe.com"
},
{
"Id": 3,
"Name": "Jeff Doe",
"EMail": "jeff#doe.com"
}
]
I am further using ng-repeat to display the values in a tabular form on my HTML.
The values are coming from an API call that fetches them from a database.
I want to swap - say the entire Object with Id 1 with the entire Object with Id 3 so that during my tabular display I can see Id 3 object details first and Id 1 object details last, without breaking any functionality.
What would be the best possible solution to do this within the frontend itself?
How about just swapping them using a temp variable?
var arr = [{"Id":1,"Name":"John Doe","EMail":"john#doe.com"},
{"Id":2,"Name":"Jim Doe","EMail":"jim#doe.com"},
{"Id":3,"Name":"Jeff Doe","EMail":"jeff#doe.com"}]
var tmpObj = arr[0];
arr[0] = arr[2];
arr[2] = tmpObj;
If you want to reverse the array, use Array.prototype.reverse()
var app = angular.module("myApp", []);
app.controller("myController", function($scope) {
var arr = [
{
"Id": 1,
"Name": "John Doe",
"EMail": "john#doe.com"
},
{
"Id": 2,
"Name": "Jim Doe",
"EMail": "jim#doe.com"
},
{
"Id": 3,
"Name": "Jeff Doe",
"EMail": "jeff#doe.com"
}
];
$scope.array = arr.reverse();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myController">
<div ng-repeat="item in array">
{{item.Id}} - {{item.Name}} - {{item.EMail}}
</div>
</div>
</div>

Json, get info within another level

I have json code that comes out like:
{
"player": [{
"player_id": "1",
"player_name": "Maxfly",
"player_image": "res_573fc05f57c0e.png",
"player_background_image": "images/player_backgrounds/581046687fd89.jpg",
"player_info": "",
"player_region": "North America",
"player_teams": [{
"id": "1",
"team_name": "Test Team",
"team_link": "test-team"
}, {
"id": "65",
"team_name": "Test Team 2",
"team_link": "test-team-2"
}]
}]
}
I've managed to get the player_id and player_name etc. My question is how to I just get the teams? I've tried the following:
$.getJSON("jsonlink",
function(data) {
$.each(data.player.player_teams, function(i,player_team){
var append_data = "<div class='item team_item'><div class='row'><div class='col col_img'><a href='/t/" + player_team.team_name + "' ></a></div></div></div>";
$("#popin-container").append($('<div>' + append_data + '</div>').hide().fadeIn(800));
});
});
Trying to figure out what I'm doing wrong. Is my json object correct?
Thanks!
Your data.player.player_teams is wrong, as data.player is an array, and not an object. You need to loop through it, or in simple way, you need to attach a [0] like this:
$.each(data.player[0].player_teams, function(i, player_team) {

Can't retrieve data from JSON in Javascript. The json is passed from php

I have a problem and i search for a solution, but i can't find it. I have this Json:
[
{
"name": "Pippo (74)",
"price": "1",
"latitudine": "10.32562",
"longitudine": "44.8003686"
},
{
"name": "pluto",
"price": "2",
"latitudine": "10.32562",
"longitudine": "44.8003686"
}
]
I want retrieve data from the Json (named msg):
num = msg.length;
document.write (num);
document.write (msg[0].name);
But it don't work! Can you help me?
You might use this parse json.
http://api.jquery.com/jquery.parsejson/
var output = jQuery.parseJSON( '[
{
"name": "Pippo (74)",
"price": "1",
"latitudine": "10.32562",
"longitudine": "44.8003686"
},
{
"name": "pluto",
"price": "2",
"latitudine": "10.32562",
"longitudine": "44.8003686"
}]' );
var list = output.data;
$.each(list,function(i,item){
console.log(item.name);
});
you can use var parsedMsg = JSON.parse(msg); to transform to a pure JS object. Then run your script. You also have a typo in 'length'
A shot in the dark here, but guessing your JSON needs to be parsed:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var parsedMsg = JSON.parse(msg);
then you can do whatever you like with the data:
num = parsedMsg.length;
console.log(num);
console.log(parsedMsg[0].name);

how to count a key name of an array from jquery/javascript?

Guys I have an array which is been encoded in json format.It looks like below :-
{"result":[{"pid":"24","uf":"hancy061","ot":"sanjit061","dn":"November 6,2015 at 02:18pm","view":"0","nu":"hancy061"},{"pid":"23","uf":"hari061","ot":"sanjit061","dn":"November 6,2015 at 01:09pm","view":"0","nu":"hari061"}]}
now in short my question is that can i count the total number of view from jquery/javascript?I want to count the view and store that number in a var.Please it might not be big deal to just count such thing.Is there any way to count that view from jquery/javascript?Help needed guys.
You can use RegExp and .match
var data = JSON.stringify({
"result": [{
"pid": "24",
"uf": "hancy061",
"ot": "sanjit061",
"dn": "November 6,2015 at 02:18pm",
"view": "0",
"nu": "hancy061"
}, {
"pid": "23",
"uf": "hari061",
"ot": "sanjit061",
"dn": "November 6,2015 at 01:09pm",
"view": "0",
"nu": "hari061"
}]
});
var count = (data.match(/view/g) || []).length;
console.log(count);

Trouble parsing json with node.js

I wrote a quick script to parse two fairly large json file (~17k records) to do a comparison of the two. I have confirmed they are both valid json (via jsonlintpro) and the same format. (The source is the same so this should be a given. But, I always assume the mistake is mine. And I still do. Just somewhere else.) However, the parsed file just outputs [object, Object]. I'm wondering what the cause could possibly be?
The json format is like this small snippet (anonymized of course):
[
{
"id": "1234",
"name": "Name1",
"url": "https://localhost/Name1",
"date_created": "2013-07-05T18:47:05Z",
"date_cancelled": "",
"props": [
{
"id": "54321",
"type": "Client",
"value": "General Store"
},
{
"id": "65432",
"type": "Contact_Name",
"value": "Joe Smith"
}
]
},
{
"id": "23456",
"name": "Name2",
"url": "https://localhost/Name2",
"date_created": "2014-02-27T17:46:43Z",
"date_cancelled": "",
"props": [
{
"id": "34567",
"type": "Client",
"value": "Bait Shop"
}
]
}]
And here is the pertinent code:
var _ = require('underscore');
var recs = require('./prod.json');
printArr(recs);
console.log(recs.length);
function printArr(arr) {
arr.forEach(function(item) {
console.log(item + ", ");
});
}
Any guidance would be greatly appreciated.
UPDATE:
Ok, so apparently the issue is with my printArr function. I'm not sure what I'm doing wrong there. I'd like to figure it out because I want to expand upon that so I can print selectively.
the parsed file just outputs [object, Object].
This is the expected behavior BECAUSE you are concatenating an object with a string.
Try console.log(item) instead
console.log(item); should indeed print [object, Object], did you try to output its properties instead?
function printArr(arr) {
arr.forEach(function(item) {
console.log( item.id, item.name, item.url, item.date_created, item.date_cancelled, item.props, ';');
});
}
Just export the value from the prod.json file.
prod.json file
module.exports = [
{
"id": "1234",
"name": "Name1"
},
{
"id": "1234",
"name": "Name1"
}]
elsewhere
var recs = require('./prod.json')
console.log(recs)

Categories

Resources