JS Object elements printing in a web page - javascript

How can I print object array elements values in a web page using document.write ?
<!DOCTYPE html> <html> <body>
<script>
var data = [
{
"metadata" : {
"names":["times","values","types"],
"types":["time","linear","ordinal"]
},
"data": [
["1141237500000",4.216,"Global_active_power"],
["1141237560000",2.4130,"Global_active_power"],
["1141237620000",3.4230,"Global_active_power"],
["1141237680000",2.4560,"Global_active_power"],
["1141237500000",2.37130,"Voltage"],
["1141237560000",2.35840,"Voltage"],
["1141237620000",0.32690,"Voltage"],
["1141237680000",10.30980,"Voltage"],
["1141237500000",13.800,"Global_intensity"],
["1141237560000",16.400,"Global_intensity"],
["1141237620000",25.400,"Global_intensity"],
["1141237680000",13.800,"Global_intensity"],
],
}
];
document.write( data["data"] );
</script> </body> </html>

You can use JSON.stringify() to convert your object in a string form, which can the be printed on your html page with document.write.
var data = [
{
"metadata" : {
"names":["times","values","types"],
"types":["time","linear","ordinal"]
},
"data": [
["1141237500000",4.216,"Global_active_power"],
["1141237560000",2.4130,"Global_active_power"],
["1141237620000",3.4230,"Global_active_power"],
["1141237680000",2.4560,"Global_active_power"],
["1141237500000",2.37130,"Voltage"],
["1141237560000",2.35840,"Voltage"],
["1141237620000",0.32690,"Voltage"],
["1141237680000",10.30980,"Voltage"],
["1141237500000",13.800,"Global_intensity"],
["1141237560000",16.400,"Global_intensity"],
["1141237620000",25.400,"Global_intensity"],
["1141237680000",13.800,"Global_intensity"],
],
}
];
var innerDataValues = data[0].data;
// document.write( JSON.stringify(data ) );
for( var i = 0; i < innerDataValues.length; i++ )
{
var value = innerDataValues[i];
document.write( value[0] + "<br />"); // 0 for timestamp
}

Related

How to construct html list by mapping with common id

i'm facing problem to construct html list.
i'm expecting same result as shown by (Expected output(Static) Below:)
Question: comm_id having same value should be constructed 1 time
here is what i'm trying
var list = [
{'com_id':12,'text':'Apple'},
{'com_id':12,'text':'Banana'},
{'com_id':91,'text':'cake'},
{'com_id':91,'text':'cup cake'},
];
var dataMap = {}, str = '';
for(var i = 0; i < list.length; i++){
if(!dataMap[list[i]['com_id']]) {
dataMap[list[i]['com_id']] = list[i];
str += '<li>com_id:'+list[i]['com_id']+' <span>'+list[i]['text']+'</span><span>'+list[i]['text']+'</span></li>';
}
}
$('#dynamic_const').html(str);
span{
display:inline-block;
padding:10px;
margin:2px;
background:#eee;
border-radius:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dynamic_const">
</div>
<p>Expected output(Static) Below:</p>
<div id="static">
<ul>
<li>com_id:12 <span>Apple</span><span>Banana</span></li>
<li>com_id:91 <span>cake</span><span>cup cake</span></li>
</ul>
</div>
Please help me thanks in advance!!!
var list = [
{'com_id':12,'text':'Apple'},
{'com_id':12,'text':'Banana'},
{'com_id':91,'text':'cake'},
{'com_id':91,'text':'cup cake'}
];
// group the text for each com_id
var reducedList = list.reduce( ( elements, element ) => {
if ( !elements[ element.com_id ] ) {
elements[ element.com_id ] = { com_id: element.com_id, text: [] }
}
elements[ element.com_id ].text.push( element.text );
return elements;
}, {} );
console.log( reducedList );
// build the html
var newHTML = Object.values( reducedList ).map( element => {
return `<li>com_id:${ element.com_id }<span>${ element.text.join( '</span><span>' ) }</span></li>`;
} );
console.log( newHTML );
If you just want to build your HTML you can use Jquery $.each
var html = '';
$.each(list, function(i, el){
html += '<li>com_id:' + el.com_id + ' <span>' + el.text + '</span></li>';
});
$('#dynamic_const').html(html);

How to populate Javascript table with JSON array?

I have JSON array similar to this :
{"X":[
{"Time":"05:45","Count":70},
{"Time":"06:30","Count":40},
{"Time":"08:15","Count":80}
]},
{"Y":[
{"Time":"09:15","Count":70},
{"Time":"10:30","Count":84},
{"Time":"12:00","Count":95}
]},
{"Z":[
{"Time":"14:00","Count":80},
{"Time":"16:00","Count":70},
{"Time":"15:00","Count":40}
]}
I have to populate table like this dynamically :
Name 05:45 06:30 08:15 09:15 10:30 12:00 14:00 16:00 15:00
X 70 40 80 0 0 0 0 0 0
Y 0 0 0 70 84 95 0 0 0
Z 0 0 0 0 0 0 80 70 40
I don't know how to populate this as Javascript table. Could anyone please help me with this?
Use JSON.parse(//your json string).
Now you can dynamically create rows by looping through this json array something like this--
var DataArray = JSON.parse(data.d);
var tableelement = $("#DataSetTbl"); //get table id from jquery
tableelement.append(createRow(DataArray)); //call this function from the action you want to show table
function createRow(Object) { //dynamically adding rows to the Table
var trElement = "<tr>"; //design this according to your requirement
for(var s=0;s<Object.length; s++)
trElement += "<td >" + Object[s].Time + "</td>";
return trElement;
}
Similarly append a new row for count :)
var data = {
"X":[
{"Time":"05:45","Count":70},
{"Time":"06:30","Count":40},
{"Time":"08:15","Count":80}
],
"Y":[
{"Time":"09:15","Count":70},
{"Time":"10:30","Count":84},
{"Time":"12:00","Count":95}
],
"Z":[
{"Time":"14:00","Count":80},
{"Time":"16:00","Count":70},
{"Time":"15:00","Count":40}
]
};
var keys = Object.keys(data), times = {}, rows = {};
(function processData(){
var row, key, r;
for(key in data) {
row = rows[key] = {};
for(r in data[key]) addInfo(row, data[key][r]);
}
function addInfo(row, record) {
times[record.Time] = true;
row[record.Time] = record.Count;
}
})();
(function createTable() {
var key,
count,
time,
tr = $('<tr>'),
$body = $('body'),
$table = $('<table>'),
$thead = $('<thead>'),
$tbody = $('<tbody>');
$body.append($table);
$table.append($thead);
$table.append($tbody);
$thead.append(tr);
tr.append('<th>name</th>');
for(time in times) tr.append('<th>'+time+'</th>');
for(key in rows) {
tr = $('<tr>');
tr.append('<th>'+key+'</th>');
for(time in times) {
count = (rows[key][time] || 0);
tr.append('<td>'+count+'</td>');
}
$tbody.append(tr);
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You would have to correct your data so it is a proper object as show in the demo below.
First so that you may be able to iterate through the times combine all the array data into array, say a
Iterate through the keys of the object and the iterate through the elements of a
If current element of a exists in the value of the outer iteration, val, then output elm.Count, otherwise output 0.
var o = {
"X":[
{"Time":"05:45","Count":70},
{"Time":"06:30","Count":40},
{"Time":"08:15","Count":80}
],
"Y":[
{"Time":"09:15","Count":70},
{"Time":"10:30","Count":84},
{"Time":"12:00","Count":95}
],
"Z":[
{"Time":"14:00","Count":80},
{"Time":"16:00","Count":70},
{"Time":"15:00","Count":40}
]
};
//merge arrays for purpose getting all times
var a = [];
$.each(o, function(k,v) {
a = a.concat( v );
});
//select table
var table = $('table');
//create row to clone
var row = $('<tr/>');
//construct header
var theadRow = row.clone().html( '<th>Name</th>' );
$.each(a, function(i,v) {
theadRow.append( '<th>' + v.Time + '</th>' );
});
//append header row to table
table.find('thead').append( theadRow );
//rows
var tbody = table.find('tbody');
$.each(o, function(key,val) {
//construct row
var tbodyRow = row.clone().html( '<th>' + key + '</th>' );
$.each(a, function(index, elm) {
tbodyRow.append( '<td>' + (val.indexOf( elm ) > -1 ? elm.Count : 0) + '</td>' );
});
//append row to table
tbody.append( tbodyRow );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead></thead>
<tbody></tbody>
</table>
Try creating valid json array of objects , utilizing $.each() , .after() , Object.keys() ; table , tr, tbody , tr , td elements ; css
$(function() {
var data = [{
"X": [{
"Time": "05:45",
"Count": 70
}, {
"Time": "06:30",
"Count": 40
}, {
"Time": "08:15",
"Count": 80
}]
}, {
"Y": [{
"Time": "09:15",
"Count": 70
}, {
"Time": "10:30",
"Count": 84
}, {
"Time": "12:00",
"Count": 95
}]
}, {
"Z": [{
"Time": "14:00",
"Count": 80
}, {
"Time": "15:00",
"Count": 70
}, {
"Time": "16:00",
"Count": 40
}]
}];
res = {};
var table = $("<table><tbody></tbody></table>");
$.each(data, function(key, value) {
var name = Object.keys(value)[0];
table.find("tbody")
.append("<tr class=" + name + "><td>" + name + "</td></tr>");
if (!res[name]) {
res[name] = [];
}
$.each(value[name], function(index, obj) {
res[name].push([obj.Count, obj.Time])
table.append("<th>" + obj.Time + "</th>");
return obj.Time
});
table.find("th").prependTo(table)
});
table.find("th:first").before("<th>Name</th>");
$.each(res, function(index, count) {
$("tr[class=" + index + "]", table).after(function() {
return $.map(Array($("th", table).length - 1), function(v, k) {
var html = count.filter(function(val) {
return val[1] === $("th", table).eq(k + 1).text()
});
return "<tr><td>" + (!!html.length ? html[0][0] : 0) + "</td></tr>"
})
})
});
table.appendTo("body")
});
table tr:not([class]),
table th {
display: inline-block;
}
table tr:not([class]) {
width: 39px;
position: relative;
left: 44px;
top:-24px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

How can I merge an Array with an object in javascript

I'm having an array of object
var todos= [
{
id: 1,
name: test,
description: test
}
]
How can I insert an object with properties stored in different variable say
var newTodos={id:2,name:test2,description:test2,purpose:NA}
so that the final arrray looks like
var todos=
[
{
id: 1,
name: test,
description: test
},
id: 2,
name: test2,
description: test2,
purpose: NA
]
var todos= [
{
id: 1,
name: test,
description: test
}
]
var newTodos={id:2,name:test2,description:test2,purpose:NA};
todos.push(newTodos);
The answer you accepted is the right answer to the wrong question.
If you really want to add the properties of newTodos (which is misnamed; it is just a single todo) then you can do what the answer says, or more easily, just do
$.extend (todos, newTodos);
_.extend (todos, newTodos);
Object.assign(todos, newTodos);
or use your other favorite property merging utility.
However, I cannot imagine what you are going to usefully do with such a mutant object, which is an array with a single element which is a todo, and now is sort of a todo itself with the todo properties directly on it.
I'm guessing that what you want to do is add another todo to your array of todos, in which case as others have suggested you can just push it.
todos.push(newTodos)
If you actually mean newTodos to be an array of todos, as its name suggests, in other words, if its format is actually
var newTodos = [ {id:2,name:test2,description:test2,purpose:NA}, ... ];
Then to add it to todos you would concatenate:
todos = todos.concat(newTodos);
This is how you do it:
for (var index in newTodos) {
todos[index] = newTodos[index];
}
You can check the values of your array like this:
for (var index in todos) {
console.log(index + ": " + todos[index]);
}
EDIT: In conform with the asked fiddle, I add the fiddle and code:
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="/js/lib/dummy.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
</style>
<script type="text/javascript">//<![CDATA[
var VanillaRunOnDomReady = function() {
var todos= [
{
id: 1,
name: 'test',
description: 'test'
}
];
var newTodos={id:2,name:'test2',description:'test2',purpose:'NA'};
for (var index in newTodos) {
todos[index] = newTodos[index];
}
var output = "";
for (var index in todos) {
if (typeof todos[index] === "object") {
output += index + ": {";
var first = true;
for (var innerIndex in todos[index]) {
if (!first) {
output += ", ";
} else {
first = false;
}
output += innerIndex + ": " + todos[index][innerIndex];
}
output += "}<br>";
} else {
output += index + ": " + todos[index] + "<br>";
}
}
document.getElementById("output").innerHTML = output;
}
var alreadyrunflag = 0;
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", function(){
alreadyrunflag=1;
VanillaRunOnDomReady();
}, false);
else if (document.all && !window.opera) {
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag = document.getElementById("contentloadtag")
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete"){
alreadyrunflag=1;
VanillaRunOnDomReady();
}
}
}
window.onload = function(){
setTimeout("if (!alreadyrunflag){VanillaRunOnDomReady}", 0);
}//]]>
</script>
</head>
<body>
<div id="output">a</div>
</body></html>

How to use jQuery built in functions in Mustache template

I have a mustache.js template
<script id="catagorie_list" type="text/template">
{{#rows}}<li>{{catagorie_name}}</li>{{/rows}}
</script>
in it, I want to make first letter of each {{catagorie_name}} as Capital Letter.
Example:
india --> India
australia-->Australia
Is it possible?
Use CSS, you might want to set a class like this on your a tag
.capitalize {text-transform:capitalize;}
And then your original code would look like
<script id="catagorie_list" type="text/template">
{{#rows}}<li><a class="capitalize" href="#">{{catagorie_name}}</a></li>{{/rows}}
</script>
Supposing the input object is:
var countries = {
"rows": [
{ "catagorie_name": "india" },
{ "catagorie_name": "australia" },
{ "catagorie_name": "spain" }
]
};
We append a function to it:
var func_var = {
"capitalize_name": function () {
return firstcap(this.catagorie_name);
}
};
jQuery.extend( countries, func_var ); // https://stackoverflow.com/a/10384883/1287812
The capitalization function:
function firstcap(str) { // https://stackoverflow.com/a/11370497/1287812
var len = str.length;
var re = /^\s$/;
var special = true; // signalizes whether previous char is special or not
for (var i=0; i<len; i++) {
var code = str.charCodeAt(i);
if (code>=97 && code<=122 && special) {
str = str.substr(0, i) + String.fromCharCode(code-32) + str.substr(i+1);
special = false;
}
else if (re.test(str[i])) {
special = true;
}
}
return str;
}
And finally, the template:
<script id="catagorie_list" type="x-tmpl-mustache">
<ul>{{#rows}}<li>{{capitalize_name}}</li>{{/rows}}</ul>
</script>

How do i make text = integers

I have a problem that i've been trying to solve for days.
I was wondering if it was possible to let a text turn into an integer.
So everytime i write in my textarea("ALC") Load, then on the textarea("MLC") 001. And also including 1-15 to binary at the end
E.g. Load #1 will show 001 0 00001
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC()";" /></p>
</form>
<script type= "text/javascript">
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = parseInt(x);
var bin = x.toString(2);
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
I think I understand what you want to do. You want to use what you type into "ALC" as a key to a value. In that case, you want to use a javascript object and assign the instructions as keys, and the binary to the value. Such as
var instruction_set = {
"Load" : "001",
"Store" : "010",
"Add" : "011",
"Sub" : "100",
"Equal" : "101",
"Jump" : "110",
"Halt" : "111"
}
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = instruction_set[x];
}
Updated:
Try this:
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC();" /></p>
</form>
<script type= "text/javascript">
var Dict = { 'Load':"001",'Store':"010"}; //example Instruction set
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
var instrType = '';
for (var instr in Dict){
var ind = x.indexOf(instr);
if( ind > -1){
instrType = instrType + Dict[instr];
x = x.replace(instr,'');
}
}
console.log(instrType, "::", x);
x = parseInt(x);
var bin = x.toString(2);
bin = instrType + bin;
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
Lets say you have a way to get the tokens. Then your function should look like this
var tokens = getTokens( document.getElementById("ALC").value ) ;
var vocabulary = { "Load" : "001" , " ... " } ;
var output = []
var i = 0;
var tokensLength = tokens.length;
for ( ; i < tokensLength; i++){
var token = tokens[i];
if ( isNaN(token) && typeof(vocabulary[token]) != "undefined" ){
output.push( vocabulary[token] );
}else if ( !isNaN(token) ){
output.push( Number(token).toString(2) );
}else{
console.log(["error : unknown token ", token]);
}
}
document.getElementById("MLC").value = output.join(" ");
I see in the question that Load translates to 0010 and not 001, so I would simply modify the vocabulary.
Explanation :
I assume you have a way to split the input to tokens. (the ALC syntax is still unclear to me).
The tokens array will contains, for example ["Load","#","15", "Load","#","16"] and so on.
Then I loop on the tokens.
If a token is a number - I turn it to binary string.
If the token is translatable by vocabulary - I switch it to its binary representation.
Otherwise I print an error.
NOTE: if output should be padded with "0" - even though it is not specified in the question, I would use "0000".substring(n.length) + n
This is how I would do it:
var opcodes = {
Load: 1,
Store: 2,
Add: 3,
Sub: 4,
Equal: 5,
Jump: 6,
Halt: 7
};
var assemblyTextarea = document.querySelector("#assembly");
var machineTextarea = document.querySelector("#machine");
document.querySelector("#assemble").addEventListener("click", function () {
var instruction = assemblyTextarea.value.split(" ");
var operand =+ instruction[1].slice(1);
var opcode = instruction[0];
var code = opcodes[opcode] * 16 + operand;
var bits = ("0000000" + code.toString(2)).slice(-8);
machineTextarea.value = bits;
}, false);
See the demo here: http://jsfiddle.net/fs5mb/1/
The input should be formatted as follows: Load #15

Categories

Resources