i have a 2d array like this
var items = [['alex',2],['alex',4],['alex',6],['jhon',11],['jhon',13]];
But in html i want to render this array like
**Names** **Numbers**
alex => 2,4,6
jhon => 11,13
You can use reduce() to return object and then Object.keys() and forEach loop to add to HTML
var items = [['alex',2],['alex',4],['alex',6],['jhon',11],['jhon',13]];
var result = items.reduce(function(r, e) {
r[e[0]] = (r[e[0]] || []).concat(e[1]);
return r;
}, {});
var rows = '';
Object.keys(result).forEach(function(e) {
rows += '<tr><td>' + e + '</td><td>' + result[e].join(',') + '</td></tr>';
});
document.querySelector('table tbody').innerHTML += rows;
<table>
<tbody>
<tr><td>Names</td><td>Numbers</td></tr>
</tbody>
</table>
Instead of reduce and array grouping I propose a jQuery approach (this is not the best solution but only a different point of view):
$(function () {
var items = [['alex',2],['alex',4],['alex',6],['jhon',11],['jhon',13]];
$.each(items, function(indexInArray, value) {
var cellIfExist = $('#result').find('td:contains(' + value[0] + ')');
if (cellIfExist.length > 0) {
cellIfExist.next().text(cellIfExist.next().text() + ', ' + value[1]);
} else {
$('#result').append('<tr><td>' + value[0] + '</td><td>' + value[1] + '</td></tr>')
}
});
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<table id="result">
<tr>
<td>**Names**</td>
<td>**Numbers**</td>
</tr>
</table>
well the old-school way is probably to iterate over the array and while doing so build an object that's pretty much like an associative array.
var items = [['alex',2],['alex',4],['alex',6],['jhon',11],['jhon',13]];
var group = { }
for(var i = 0; i < items.length; i++) {
var pair = items[i];
if(group[pair[0]]) {
group[pair[0]].push(pair[1]);
}
else {
group[pair[0]] = [pair[1]];
}
}
"group" is then your grouped object. Iterate over it using a for-loop.
Simple solution using Array.forEach function:
var items = [['alex',2],['alex',4],['alex',6],['jhon',11],['jhon',13]],
names = {};
items.forEach(function (arr) {
(names[arr[0]])? names[arr[0]].push(arr[1]) : (names[arr[0]] = [arr[1]]);
});
console.log(JSON.stringify(names, 0, 4));
Related
JSON: https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py
Im trying to fetch objects and arrays within the object but im only fetching the objects.
How do i fetch also "products" arrays?
My javascript code:
fetch('https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py')
.then(res => res.text())
.then(teksti => tulostus(teksti))
function tulostus(txt) {
console.log(txt);
let tilaukset = JSON.parse(txt);
console.log(tilaukset);
let a = "<table><tr><th>orderid</th><th>customerid</th><th>customer</th><th>invaddr</th><th>delivaddr</th><th>deliverydate</th><th>respsalesperson</th><th>comment</th><th>totalprice</th></tr>";
for(let i = 0; i < tilaukset.length; i++) {
let tilaus = tilaukset[i];
console.log(tilaus)
console.log(tilaus.orderid);
a += '<tr><td>' + tilaus.orderid + '</td><td>' + tilaus.customerid + '</td><td>' + tilaus.customer + '</td><td>' + tilaus.invaddr + '</td><td>' + tilaus.delivaddr + '</td><td>' + tilaus.deliverydate + '</td><td>' + tilaus.respsalesperson + '</td><td>' + tilaus.comment + '</td><td>' + tilaus.totalprice + '</td></tr>'
}
console.log(a);
document.getElementById('info').innerHTML = a+'</table>';
}
You likely are fetching the products array but need to add some code to iterate over it.
for(let i = 0; i < tilaukset.length; i++) {
let tilaus = tilaukset[i];
console.log(tilaus)
console.log(tilaus.orderid);
a += '...'
for (let j=0; j < tilaus.products.length; j++) {
console.log(tilaus.products[i].name);
}
}
Replace the console log in the loop with some code to write to the html as you were doing above. Depending on how you'd like it to look at might get tricky, so consider abstracting away HTML generation or using a library that helps you componentize the ui.
fetch("https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py").
then(response => response.json())
.then(result => display(result))
let display = (result) => {
for (let i = 0; i < result.length; i++) {
let products = result[i].products
// here products is a Object array
for(let i=0;i<products.length;i++){
let product = products[i];
console.log(product)
// add your stuff here like product.orderid to get orderid
}
}
}
you're already looping over the array and getting the object from there, if you check there's product array there in every array value(tialus.products) just save that value in a variable
I have multiple tables. when looping through each table.innerHtml print all tables one by one.but when convert into object it only gives one table object.
$( ".table" ).each(function( index ,e) {
let tableId = $(this).closest('table').attr('id')
var table = document.getElementById(tableId);
console.table(table.innerHTML+"tb");
let myObj = {
table: [],
add_rows: []
};
for (var i = 0; row = table.rows[i]; i++) {
let tr_obj = [];
for (var j = 0; col = row.cells[j]; j++) {
var drop_down = $("#drop\\[" + j + "\\]").val()
var text_value = $("#text\\[" + i + "\\]\\[" + j + "\\]").val();
tr_obj.push(create_object(drop_down, text_value));
}
myObj['table'].push(tr_obj);
}
console.log(JSON.stringify(myObj['table'])+"ttt")
var div="div"+tableId
var hidden="entry_field_"+tableId+""
document.getElementById(hidden).value = JSON.stringify(myObj).replace(/\\/g, "")
});
when we console table.InnerHtml it gives print both table.but MyObj gives same table object.
I've improved your fiddle and myObj is created correctly (in table property are rows from both tables). But if you want render this object in json format you have to redesign this object or render the same object in two tables. If you want render two objects with different tables prop you have to convert myObj in to separate objects. Look on my fiddle:
table.forEach((e,i)=>{
let tr_obj = [];
Array.from(e.rows).forEach((ele,ind)=>{
let cells = []
Array.from(ele.cells).forEach((element,index)=>{
let drop_down = $("#drop\\[" + i + "\\]\\[" + ind + "\\]\\[" + index + "\\]").val();
let text_value = $("#text\\[" + i + "\\]\\[" + ind + "\\]\\[" + index + "\\]").val();
cells.push(create_object(drop_down, text_value));
})
tr_obj.push(cells)
});
myObj['table'].push(tr_obj);
});
And fiddle: https://jsfiddle.net/wa3vbsc6/2/
I am requesting data from a json to fill a table. I want to limit to 5 the request.
jQuery.getJSON("data/data.json", function(data) {
var table = $("table");
$.each(data, function(id, elem) {
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
});
})
Or another option is to add boolean key "active" to the data and that it brings me the data items with the value = true. How do i do this?
You can use .slice() to filter the returned array down to just the first 5 elements.
data = data.slice(0, 5);
Just use a simple for loop.
var json_arr, limit;
limit = 5; // set limit to whatever you like
json_arr = JSON.parse(json_data);
for(var i = 0; i < limit; i++;) {
var this_item = json_arr[i];
table.append(this_item); // do your thing
}
The best limit you can implement is on your own controller (where you get your data from)
But if you don't have access/don't want to change, you can simple achive this by JavaScript:
var limit = 5; //your Limit
for(var i in data){
if(i > limit) break;
var elem = data[i];
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
}
var table =$("#exampleList").DataTable({
paging:false,
rowReorder:false
}
});
table.on('row-reorder',function(e, diff,edit){
for(var i=0, ien = diff.length ; i<ien ; i++){
var rowData = table.row(diff[i].node).data();
sequence = sequence + "_" + rowData[0];
}
var data = table.rows().data();
data.each(function (value, index) {
alert('Data in index: ' + index + ' is: ' + value);
});
});
Hi,
I am new to datatables. Issue I am having right now is I cant get the latest value in my table after the user reorder the row. The code above only shows the value before the reorder occurs. I need to get the latest reorder sequence so I can update the database.
What you need to do is wait a few milliseconds before trying to read the data.
table.on('row-reorder',function(e, diff, edit){
for(var i=0, ien = diff.length ; i<ien ; i++){
var rowData = table.row(diff[i].node).data();
sequence = sequence + "_" + rowData[0];
}
setTimeout(()=> { lookAtData() }, 10);
});
function lookAtData() {
var data = table.rows().data();
data.each(function (value, index) {
alert('Data in index: ' + index + ' is: ' + value);
});
}
You should use column-reorder not row-reorder.
Please try :
var rdata = table .columns().order().data();
console.log(rdata);
It will get the data after columns ordering.
I want to navigate each property in the JSON below in JavaScript. The below JSON contains two records for reference but in real time will have numerous such records.
{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}
I want to get the values of the fields "Status", "CreatorLoginId" and "Name" to assign them to something else.
How should I do it?
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var pr in myJSON)
{
console.log(myJSON[pr][0].Status);
console.log(myJSON[pr][0].CreatorLoginId);
console.log(myJSON[pr][0].Name);
}
Print how? If you mean output to the js console it would be
for (index in object) {
console.log(index + ': ' + object[index]);
}
If you mean add it to a web page, just replace console.log with a little markup:
var parent = document.getElementById('parentID');
for (index in object) {
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
For nested objects (including arrays)
function print(object, parent) {
for (index in object) {
if (typeof object[index] == 'object') {
print(object[index});
}
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
}
EDIT: don't forget to JSON.parse(): the string first before iterating
//Iterating through the groups
for (var currentRecord in groupInformation)
{
store.data.items.push({serial: {}, groupName: {}, createdBy: {}, status: {} });
store.data.items[iNoOfGroups].serial = iNoOfGroups + 1;
store.data.items[iNoOfGroups].groupName = groupInformation[currentRecord][0].Name;
store.data.items[iNoOfGroups].createdBy = groupInformation[currentRecord][0].CreatorLoginId;
store.data.items[iNoOfGroups].status = groupInformation[currentRecord][0].Status;
iNoOfGroups++;
}
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var key in myJSON){
console.log(myJSON[key][0].Status);
console.log(myJSON[key][0].CreatorLoginId);
console.log(myJSON[key][0].Name);
}`