Format returned table data in json - javascript

I'm fairly new to javascript. I retreive data from a sql server database that looks like this :
[Object { shortcode="0013A2004031AC9A", latest_measurement=1067, keyid="6801"},
Object { shortcode="0013A2004031AC9A", latest_measurement=7, keyid="6802"},
Object { shortcode="0013A2004031AC9A", latest_measurement=8598838, keyid="6803"}]
I want to format this in a json like this :
{mac : 0013A2004031AC9A, keys : {6801:1067, 6802:7, 6803:8598838}}
but I just don't get to that.
I have
var jsonDataPerMac = {};
I loop over the json object above and for every new mac I find I do :
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
but how do I get to fill the keys?
Any hints would be appreciated.enter code here
var macs = [];
var jsonDataPerMac = {};
var i = 0;
$.ajax({
url: "/bmmeasurements",
type: "GET",
data: {"unitid" : unitid},
async: false,
success: function (data) {
console.log(data);
initializeTable();
$.each(data, function (index,device) {
//add all distinct macs in an array, to use them as a column header
if($.inArray(device.shortcode, macs) == -1) {
macs.push(device.shortcode);
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
i++;
//create a table cell for each possible key. id = 'mac-key'
createTableGrid(device.shortcode);
}
//add the measurement data to the correct cell in the grid
$('#' + device.shortcode + '-' + device.keyid).html(device.latest_measurement);
});
}});

Here is my proposition. I would rather avoid using jQuery to perform such a simple operations. In this particular example, we use forEach and for..in loop.
//new output array
var newArray = [];
//we traverse the array received from AJAX call
array.forEach(function(el) {
var added = false; // it's false by default
// we check if the mac is already in newArray, if yes - just add the key
for(var i in newArray) {
if(newArray[i].mac == el.shortcode) {
newArray[i].keys.push(el.keyid+":"+el.latest_measurement);
added = true; // tells us whether the key has been added or not
}
}
// if key hasn't been added - create a new entry
if(!added) {
newArray.push({"mac": el.shortcode, "keys":[el.keyid+":"+el.latest_measurement]});
}
});
console.log(newArray);
You can transform above code to a function and then, reuse it in your ajax onSuccess method. Remember to pass the array as an argument and to return newArray.
JSFiddle:
http://jsfiddle.net/2d5Vq/2/

You need to combine the entries first...
var reducedData = {};
$.each(macs, function(index,macitem){
if (reducedData.hasOwnProperty(macitem.shortcode)) {
reducedData[macitem.shortcode].push(macitem.key);
} else {
reducedData[macitem.shortcode] = [ macitem.key ];
}
});
And then map to your desired format inside an array...
var jsonDataPerMac = [],
i = 0;
$.map(reducedData, function(keys,mac){
jsonDataPerMac[i++] = {"mac": mac, "keys": keys};
// your other code goes here
});
Also your usage of jsonDataPerMac suggests that you want it to be an array.

Related

How to update JavaScript array dynamically

I have an empty javascript array(matrix) that I created to achieve refresh of divs. I created a function to dynamically put data in it. Then I created a function to update the Array (which I have issues).
The Data populated in the Array are data attributes that I put in a JSON file.
To better undertand, here are my data attributes which i put in json file:
var currentAge = $(this).data("age");
var currentDate = $(this).data("date");
var currentFullName = $(this).data("fullname");
var currentIDPerson = $(this).data("idPerson");
var currentGender = $(this).data("gender");
Creation of the array:
var arrayData = [];
Here is the function a created to initiate and addind element to the Array :
function initMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
var isFound = false;
// search if the unique index match the ID of the HTML one
for (var i = 0; i < arrayData.length; i++) {
if(arrayData[i].idPerson== p_currentIDPerson) {
isFound = true;
}
}
// If it doesn't exist we add elements
if(isFound == false) {
var tempArray = [
{
currentIDPerson: p_currentIDPerson,
currentGender: p_currentGender,
currentFullName: p_currentFullName,
currentDate: p_currentDate, currentAge: p_currentAge
}
];
arrayData.push(tempArray);
}
}
The update function here is what I tried, but it doesn't work, maybe I'm not coding it the right way. If you can help please.
function updateMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
for (var i = 0; i < arguments.length; i++) {
for (var key in arguments[i]) {
arrayData[i] = arguments[i][key];
}
}
}
To understand the '$this' and elm: elm is the clickableDivs where I put click event:
(function( $ ) {
// Plugin to manage clickable divs
$.fn.infoClickable = function() {
this.each(function() {
var elm = $( this );
//Call init function
initMatrixRefresh(elm.attr("idPerson"), elm.data("gender"), elm.data("fullname"), elm.data("date"), elm.data("age"));
//call function update
updateMatrix("idTest", "Alarme", "none", "10-02-17 08:20", 10);
// Définition de l'evenement click
elm.on("click", function(){});
});
}
$('.clickableDiv').infoClickable();
}( jQuery ));
Thank you in advance
Well... I would recommend you to use an object in which each key is a person id for keeping this list, instead of an array. This way you can write cleaner code that achieves the same results but with improved performance. For example:
var myDataCollection = {};
function initMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
if (!myDataCollection[p_currentIDPerson]) {
myDataCollection[p_currentIDPerson] = {
currentIDPerson: p_currentIDPerson,
currentGender: p_currentGender,
currentFullName: p_currentFullName,
currentDate: p_currentDate,
currentAge: p_currentAge
};
}
}
function updateMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
if (myDataCollection[p_currentIDPerson]) {
myDataCollection[p_currentIDPerson] = {
currentGender: p_currentGender,
currentFullName: p_currentFullName,
currentDate: p_currentDate,
currentAge: p_currentAge
};
}
}
Depending on your business logic, you can remove the if statements and keep only one function that adds the object when there is no object with the specified id and updates the object when there is one.
I think the shape of the resulting matrix is different than you think. Specifically, the matrix after init looks like [ [ {id, ...} ] ]. Your update function isn't looping enough. It seems like you are trying to create a data structure for storing and updating a list of users. I would recommend a flat list or an object indexed by userID since thats your lookup.
var userStorage = {}
// add/update users
userStorage[id] = {id:u_id};
// list of users
var users = Object.keys(users);

Javascript object to array, length = 0

I'm building a webshop where users are able to add products for one of more stores in their basket and checkout (like AliExpress).
On the cart overview page, the content of the basket is shown sorted by store. If the same product is added multiple times over different stores, the product is show by every store.
Now, I want to create an order for every store with the products ordered by that store. I'm using Angular to create the list with products ordered/filtered by store.
That data will be sent to my Node.JS server, to loop the contents and create some orders with items.
The problem, I think, is that the data is processed like a 'object' and not an 'array'. I have found a function which converts a object to an array, but the length is still '0'.
How can I process the data so I can loop through the different items?
AngularJS code to sort cart by store
$scope.filterProducts = function(groupName) {
$scope.productList = [];
$http({
method: 'GET',
xhrFields: {withCredentials: true},
url: '/loadCart'
}).then(function successCallback(response){
if (response.data) {
var mapByShop = function(arr, groupName) {
return arr.reduce(function(result, item) {
result[item[groupName]] = result[item[groupName]] || {};
result[item[groupName]][item['productId']] = item;
console.log('GROUPNAME en RESULT', groupName, result);
return result;
}, {});
};
if (response.data.length > 0) {
if (groupName == 'shopName') {
$scope.productList = mapByShop(response.data, groupName);
} else {
$scope.checkoutList = mapByShop(response.data, groupName);
}
}
}
}, function errorCallback(response){
console.log(response);
});
}
The $scope.productList is sent as 'data' in a $http POST function.
Node.JS code to convert an object to an array
function convertObjectToArray(object, cb){
var cartContent = [];
for (var i in object) {
cartContent[i] = object[i];
}
console.log("convertObjectToArray");
return cb(cartContent);
}
Code to process the data (where length is zero)
convertObjectToArray(req.body.cart, function(result){
console.log(isArray(result));
console.log('result', result);
console.log("lenght", result.length);
})
FYI: the isArray function
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
if array order is not important, you should use
cartContent.push(object[i]);
It will update the .length property automaticly
Your problem is that you are adding properties to the array object, and not using the Array API to insert at integer locations in the object. This means the array essentially remains "empty". If you key on an integer when inserting into the array then your code will work better.
The broken bit:
for (var i in object) {
cartContent[i] = object[i];
}
i is a string key here and will not increment the length of the Array unless the value coerces to an integer value (I think).
Something like this might work:
// Untested...
var keys = Object.keys(object);
for (var i = 0; i < keys.length; i++) {
cartContent[i] = object[keys[i]];
}
Or like the other answer suggested, use the push API.
Aside:
If you are in a modern JS engine you can:
Use Object.values, or
Write a couple of utility functions and convert an object to an array using the following
:
var o = iterable({foo:'fooValue', bar: 'barValue'});
console.log([...o]);
The utility functions:
function iterable(o) {
if(o[Symbol.iterator]) {
return o;
}
o[Symbol.iterator] = iter.bind(null, o);
return o;
}
function* iter(o) {
var keys = Object.keys(o);
for (var i=0; i<keys.length; i++) {
yield o[keys[i]];
}
}

HTML5 nested data-* attributes parsed with Javascript don't return a nested object

I am stuck in a concept of html5 data attributes. That attributes allows nesting like:
<div data-user--name="John" data-user--surname="Doe"></div>
I have seen plugins in the past (like select2) and some of them use the following similar syntax to make an AJAX call:
<div data-ajax--url="my/url" data-ajax--method="POST">
This code in background converts to a dataset in javascript and it returns something like this:
data = {
ajax: {
url: "my/url",
method: "POST"
}
}
But in the practice, vanilla javascript's dataset and jQuery data() methods return different object content.
Javascript
var el = document.getElementsByTagName("div")[0];
el.innerHTML = "<pre>"+JSON.stringify(el.dataset)+"</pre>";
<div data-ajax--url="my/url" data-ajax--method="POST"></div>
jQuery 1.x
$('div').html("<pre>"+JSON.stringify($('div').data())+"</pre>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-ajax--url="my/url" data-ajax--method="POST"></div>
jQuery 2.x
$('div').html("<pre>"+JSON.stringify($('div').data())+"</pre>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-ajax--url="my/url" data-ajax--method="POST"></div>
The code in error seems to be the jQuery 1.x versions, because in 2.x versions jQuery returns the same as vanilla Javascript. I found a related bug so it's confirmed: https://github.com/select2/select2/issues/2969
But I can't find where to construct a nested javascript object with the nested html syntax, like the following example:
{
ajax: {
url: "my/url"
method: "POST"
}
}
Is there any Javascript method, or a polyfill, that makes this kind of objects reading the data-* HTML attributes? Is it possible to parse the data javascript strings (i.e. ajax-Method) and return a nested object (ajax.method) ?
Ran into exact same need, but #artofcode's answer parses only 2 levels. So I had to figure out how to parse unlimited number of levels. Here's my solution without limiting levels, based on original answer.
function parseNestedDataSet(data_set) {
var keys = Object.keys(data_set);
var data = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = data_set[key];
var splat = key.split('-');
data = parseNestedDataSetKey(splat, value, data);
}
return data;
}
function parseNestedDataSetKey(keys, value, data) {
data = data || {};
var key = keys[0].toLowerCase();
// Not tested, but should convert to camel case
// var key = keys[0].replace(/-([a-z])/g, function (g) {
// return g[1].toUpperCase();
// });
if (!data[key]) {
data[key] = {};
}
if (keys.length > 1) {
keys.splice(0, 1);
data[key] = parseNestedDataSetKey(keys, value, data[key]);
} else {
data[key] = value;
}
return data;
}
Didn't test it thoroughly, but it works in my case, like:
data-buttons--btn1--title;
data-buttons--btn1--icon;
data-buttons--btn2--title.
function parseDataset(dataset) {
data = {};
for(var i = 0; i < Object.keys(dataset).length; i++) {
var key = Object.keys(dataset)[i];
var value = dataset[key];
var splat = key.split("-");
console.log(key, data, splat);
if(!data[splat[0]]) {
data[splat[0]] = {};
}
data[splat[0]][splat[1]] = value;
}
return data;
}
Untested, but should work. Pass el.dataset into the method, get a data object out like:
data = {
'ajax': {
'Method': 'POST',
'Url': 'my/url'
}
};

How to make 1 variable is equal to multiple values?

Hello I want to add friends on facebook using tokens..
I found this code.
edprens: function(a) {
if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: USER ID/NAME I WANT TO ADD,
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}
},
example I have.. ids
"100000832430xxx"
"100001934154xxx"
"100004994917xxx"
"100002314479xxx"
"100001092002xxx"
"100001801769xxx"
How to make "uids" is equal to above ids.. so I can add them.?
Thank you
It's too big to post it in comment. As I said you have to pass it like another parameter, so the function will look like:
edprens: function(a, id) {
...
uids: id, // USER ID/NAME YOU WANT TO ADD
...
}
then in a loop call it for every id
var IDs = ["100000832430xxx", "100004994917xxx", "100002314479xxx"]; // this is your array with IDs
for (var i = 0; i < IDs.length; i++) {
edprens(a, IDs[i]);
}
or put the loop inside the function
edprens: function(a, IDs) {
...
for (var i = 0; i < IDs.length; i++) {
$.getJSON("https://graph.facebook.com/me/friends", {
...
uids: IDs[i], // USER ID/NAME YOU WANT TO ADD
...
});
}
...
}
edprens("ids###");edprens("ids###");edprens("ids###"); is not a loop. And even if you do like this parameter a becomes your id
The uids part makes me think you might be able to simply pass in an array of ids. Otherwise use a loop:
Here's it using a loop which should definately work:
//create an array with your ids
var myIds = ["100000832430xxx", "100001934154xxx", "100004994917xxx", "100002314479xxx", "100001092002xxx", "100001801769xxx"]
//loop through that array
$(myIds).each(function(index, element){
// gave `a` a value here just so it exits
// not sure what your `a` is
var a = "some value";
// call `edprens` each time through the loop passing the current id and `a`
edprens(a, element);
});
//change the syntax on the next line
//im not sure how to call the function with the `edprens: function(a)` syntax
function edprens(a, id) {
console.log('function would have been called with id:'+id);
// im commenting out the rest since it requires other code not present
/*if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: id,
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}*/
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's it passing an array which might work?...:
//second method (possible but not sure)
//the `uids` part makes me think you might be ale to simply pass in an array of ids like:
var myIds = ["100000832430xxx", "100001934154xxx", "100004994917xxx", "100002314479xxx", "100001092002xxx", "100001801769xxx"]
var a = "some value";
// im commenting out the funnction call
// on the next line since it requires other code not present
//edprens(a, myIds)
//changed
function edprens2(a, id) {
if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: myIds, //here we supply the whole array, might work but Im not familar with the rest of the process so I cant say for sure
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}
};

How to serialize delete data with jqGrid, multiselection, and Spring?

Currently, I have an overridden delGridRow call that looks like this (credit to Krams and his Spring tutorial):
var row = $('#grid').jqGrid('getGridParam','selrow');
$('#grid').jqGrid( 'delGridRow', row,
{ url:'deleteRequirement.html',
recreateForm: true,
beforeShowForm: function(form) {
//Change title
$(".delmsg").replaceWith('<span style="white-space: pre;">' +
'Delete selected record?' + '</span>');
//hide arrows
$('#pData').hide();
$('#nData').hide();
},
reloadAfterSubmit:true,
closeAfterDelete: true,
serializeDelData: function (postdata) {
var rowdata = $('#grid').getRowData(postdata.id);
// append postdata with any information
return {id: postdata.id, oper: postdata.oper, reqID: rowdata.reqID};
},
afterSubmit : function(response, postdata)
{
var result = eval('(' + response.responseText + ')');
var errors = "";
if (result.success == false) {
for (var i = 0; i < result.message.length; i++) {
errors += result.message[i] + "<br/>";
}
} else {
$('#msgbox').text('Entry has been deleted successfully');
$('#msgbox').dialog(
{ title: 'Success',
modal: true,
buttons: {"Ok": function() {
$(this).dialog("close");
}
}
});
}
// only used for adding new records
var newId = null;
return [result.success, errors, newId];
}
});
else {
$('#msgbox').text('You must select a record first!');
$('#msgbox').dialog(
{ title: 'Error',
modal: true,
buttons: {"Ok": function() {
$(this).dialog("close");}
}
});
}
In order to add support for multiselection deletes, I changed the "selrow" first line to this:
var rowList = jQuery("#grid").getGridParam('selarrrow');
After this, things start getting sketchy fast. The spec says that the default delGridRow can accept an array of inputs records to delete. I made the following change to attempt to get the new 'rowList' variable to get used:
$('#grid').jqGrid( 'delGridRow', rowList, ...
I'm still hitting my deleteRequirement.html URL in my Spring controller, but only the last records appears to make it. I'm guessing the problem is in the postdata preparation in the serializeDelData section, but I haven't found the correct way to prepare this postdata with the list of records instead of the single record.
Any suggestions/insight would be appreciated.
Thanks all.
I don't use Spring myself, but some parts of your code seams be strange for me.
First of all the you can use two forms of the first parameter of delGridRow (row in your code). It can be either the comma-separated list of ids or an array of ids. If you use array of ids then jqGrid convert it to the comma-separated format by rowids = rowids.join();. As the result the format of postdata.id inside of serializeDelData can be also the comma-separated list of ids.
So if you need to support delete of multiple rows you should
modify the code of serializeDelData to send in reqID property also the list of the reqID. The corresponding code can be
serializeDelData: function (postdata) {
var ids = postdata.id.split(','), i, l = ids.length, reqIDList = [];
for (i = 0; i < l; i++) {
reqIDList.push($(this).jqGrid("getCell", ids[i], "reqID"));
}
return {id: postdata.id, oper: postdata.oper, reqID: reqIDList.join()};
}
modify your server code to support both id and reqID in comma-separated form.
Inside of afterSubmit callback you you the lines
// only used for adding new records
var newId = null;
return [result.success, errors, newId];
You can modify the lines to the following
return [result.success, errors];
because only the first two elements of the array returned by afterSubmit callback will be used.

Categories

Resources