Javascript object to array, length = 0 - javascript

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]];
}
}

Related

JavaScript Obj.length method returns undefined despite dictionary containing elements

I've been working on a project and I'm currently working on a function which dynamically creates a dictionary data structure. The key used is the roll number of the student, and the value is the student's name.
But I'm unable to iterate through this dictionary. I've tried displaying the dictionary on console, but all I could see is an empty dictionary. I could see the elements in it, only if I expand it further. And when I display length using Obj.length on console, it displays 'undefined'. I've read on other questions that Obj.length only works on arrays(i.e., enumerable types), and I've tried using an array instead of a dictionary. In that case, it shows an empty array and would not show values unless I manually expand it. I've also tried Obj.keys() method on the dictionary, and I've encountered the same issue.
This is the function's code:
function dictGenerator(rollnos, selectedValue) {
var dict = {};
for(let i = 0; i < rollnos.length; i++) {
get(child(dbref, "RegisterNos/" + rollnos[i])).then((snapshot)=>{
if(Object.keys(snapshot.val()).length-1 == selectedValue){
dict[rollnos[i]] = snapshot.val()["name"];
}
});
}
console.log(dict);
console.log(dict.length);
}
}
Any help on how I could iterate through my dictionary would be appreciated, Thank you.
Edit:
code implementation using promises.
function dictGenerator(regnos, selectedValue) {
const get_dict = async () => {
var dict = {};
for(let i = 0; i < regnos.length; i++){
get(child(dbref, "RegisterNos/" + regnos[i])).then((snapshot)=>{
if(Object.keys(snapshot.val()).length-1 == selectedValue){
dict[regnos[i]] = snapshot.val()["name"];
}
});
}
return dict;
};
get_dict().then((dict) => {
console.log(dict);
});
}
Basing on comments made by VALZ and JaredSmith, this is the working code:
function dictGenerator(regnos, selectedValue) {
const get_dict = async () => {
var dict = {};
for(let i = 0; i < regnos.length; i++){
await get(child(dbref, "RegisterNos/" + regnos[i])).then((snapshot)=>{
if(Object.keys(snapshot.val()).length-1 == selectedValue){
dict[regnos[i]] = snapshot.val()["name"];
}
});
}
return dict;
};
get_dict().then((dict) => {
console.log(dict);
});
}
}

Detect differences between two objects (JSON)

I've got a remote JSON file that contains the list of the last 100 users who logged into a service. This JSON is updated constantly and lists the users from the most recently logged in to the "least recently" logged in.
If the user who appears as number X logs back in, they get removed from their position X and put back at the very top of the JSON at position [0].
I retrieve the JSON every 5 minutes. What I'd like to do is detect the differences between the old object oldUsers and the new newUsers and store them in another object that would only contain the users who are present in newUsers but not in oldUsers. I have no real idea as to how to achieve this.
Here's the JSON structure:
[{
"id":"foo09",
"name":"John",
"age":28
}, {
"id":"bar171",
"name":"Bryan",
"age":36
},
...
]
Is there a rather straightforward way to do it? Thanks!
You need to write your own diff algorithm. Here is one I whipped up in JSBin:
I will need a utility function to merge two arrays (Underscore would help here).
function mergeArrays(val1, val2) {
var results = val1.splice(0);
val2.forEach(function(val) {
if (val1.indexOf(val) < 0) {
results.push(val);
}
});
return results;
}
Diff algorithm
function diff(val1, val2) {
var results = [];
var origKeys = Object.keys(val1);
var newKeys = Object.keys(val2);
mergeArrays(origKeys, newKeys)
.forEach(function(key) {
if (val1[key] === val2[key]) { return; }
var result = {
key: key,
orig: val1[key],
'new': val2[key]
};
if (val1[key] == null) {
result.type = 'add';
} else if (val2[key] == null) {
result.type = 'delete';
} else {
result.type = 'change';
}
results.push(result);
});
return results;
}

Format returned table data in json

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.

return from JS function

basic JS question, please go easy on me I'm a newb :)
I pass 2 variables to the findRelatedRecords function which queries other related tables and assembles an Array of Objects, called data. Since findRelatedRecords has so many inner functions, I'm having a hard time getting the data Array out of the function.
As it currently is, I call showWin inside findRelatedRecords, but I'd like to change it so that I can get data Array directly out of findRelatedRecords, and not jump to showWin
function findRelatedRecords(features,evtObj){
//first relationship query to find related branches
var selFeat = features
var featObjId = selFeat[0].attributes.OBJECTID_1
var relatedBranch = new esri.tasks.RelationshipQuery();
relatedBranch.outFields = ["*"];
relatedBranch.relationshipId = 1; //fac -to- Branch
relatedBranch.objectIds = [featObjId];
facSel.queryRelatedFeatures(relatedBranch, function(relatedBranches) {
var branchFound = false;
if(relatedBranches.hasOwnProperty(featObjId) == true){
branchFound = true;
var branchSet = relatedBranches[featObjId]
var cmdBranch = dojo.map(branchSet.features, function(feature){
return feature.attributes;
})
}
//regardless of whether a branch is found or not, we have to run the cmdMain relationship query
//the parent is still fac, no advantage of the parent being branch since cmcMain query has to be run regardless
//fac - branch - cmdMain - cmdSub <--sometimes
//fac - cmdMain - cmdSub <-- sometimes
//second relationship query to find related cmdMains
var relatedQuery = new esri.tasks.RelationshipQuery();
relatedQuery.outFields = ["*"];
relatedQuery.relationshipId = 0; //fac -to- cmdMain
relatedQuery.objectIds = [featObjId];
//rather then listen for "OnSelectionComplete" we are using the queryRelatedFeatures callback function
facSel.queryRelatedFeatures(relatedQuery, function(relatedRecords) {
var data = []
//if any cmdMain records were found, relatedRecords object will have a property = to the OBJECTID of the clicked feature
//i.e. if cmdMain records are found, true will be returned; and continue with finding cmdSub records
if(relatedRecords.hasOwnProperty(featObjId) == true){
var fset = relatedRecords[featObjId]
var cmdMain = dojo.map(fset.features, function(feature) {
return feature.attributes;
})
//we need to fill an array with the objectids of the returned cmdMain records
//the length of this list == total number of mainCmd records returned for the clicked facility
objs = []
for (var k in cmdMain){
var o = cmdMain[k];
objs.push(o.OBJECTID)
}
//third relationship query to find records related to cmdMain (cmdSub)
var subQuery = new esri.tasks.RelationshipQuery();
subQuery.outFields = ["*"];
subQuery.relationshipId = 2;
subQuery.objectIds = [objs]
subTbl.queryRelatedFeatures(subQuery, function (subRecords){
//subRecords is an object where each property is the objectid of a cmdMain record
//if a cmdRecord objectid is present in subRecords property, cmdMain has sub records
//we no longer need these objectids, so we'll remove them and put the array into cmdsub
var cmdSub = []
for (id in subRecords){
dojo.forEach(subRecords[id].features, function(rec){
cmdSub.push(rec.attributes)
})
}
var j = cmdSub.length;
var p;
var sub_key;
var obj;
if (branchFound == true){
var p1 = "branch";
obj1 = {};
obj1[p1] = [cmdBranch[0].Branches]
data.push(obj1)
}
for (var i=0, iLen = cmdMain.length; i<iLen; i++) {
p = cmdMain[i].ASGMT_Name
obj = {};
obj[p] = [];
sub_key = cmdMain[i].sub_key;
for (var j=0, jLen=cmdSub.length; j<jLen; j++) {
if (cmdSub[j].sub_key == sub_key) {
obj[p].push(cmdSub[j].Long_Name);
}
}
data.push(obj);
}
showWin(data,evtObj) <---this would go away
})
}
//no returned cmdRecords; cmdData not available
else{
p = "No Data Available"
obj = {}
obj[p] = []
data.push(obj)
}
showWin(data,evtObj) <--this would go away
})
})
}
I'd like to have access to data array simply by calling
function findRelatedRecords(feature,evt){
//code pasted above
}
function newfunct(){
var newData = findRelatedRecords(feature,evt)
console.log(newData)
}
is this possible?
thanks!
Edit
Little more explanation.....
I'm connecting an Object event Listener to a Function like so:
function b (input){
dojo.connect(obj, "onQueryRelatedFeaturesComplete", getData);
obj.queryRelatedFeatures(input);
console.log(arr) //<----this doesn't work
}
function getData(relatedFeatData){
var arr = [];
//populate arr
return arr;
}
So when obj.QueryRelatedFeatures() is complete, getData fires; this part works fine, but how to I access arr from function b ?
Post Edit Update:
Due to the way that this event is being hooked up you can't simple return data from it. Returning will just let Dojo call to the next method that is hooked up to onSelectionComplete.
When init runs it is long before findRelatedRecords will ever be executed/fired by the onSelectionComplete event of the well, which is why you were seeing undefined/null values. The only way to work with this sort of system is to either 1) call off to a method like you're already doing or 2) fire off a custom event/message (technically it's still just calling off to a method).
If you want to make this method easier to work with you should refactor/extract snippets of it to make it a smaller function but contained in many functions. Also, changing it to have only one exit point at the end of the findRelatedRecords method will help. The function defined inside of subTbl.queryRelatedFeatures() would be a great place to start.
Sorry, you're kind of limited by what Dojo gives you in this case.
Pre Edit Answer:
Just return your data out of it. Everywhere where there is a showWin call just use this return.
return {
data: data,
evtObj: evtObj
}
Then your newfunct would look like this.
function newfunct(){
var newData = findRelatedRecords(feature,evt);
console.log(newData);
console.log(newData.data);
console.log(newData.evtObj);
}
If you only need that "data" object, then change your return to just return data;.
Also, start using semicolons to terminate statements.

Advanced search/queue array collection question

I have a pretty large number of objects "usrSession" I store them in my ArrayCollection usrSessionCollection.
I'M looking for a function that returns the latest userSessions added with a unique userID. So something like this:
1.
search the usrSessionCollection and only return one userSessions per userID.
2.
When it has returned x number of userSessions then deleted them from the usrSessionCollection
I'M stuck - would really love some code that can help me with that.
function ArrayCollection() {
var myArray = new Array;
return {
empty: function () {
myArray.splice(0, myArray.length);
},
add: function (myElement) {
myArray.push(myElement);
}
}
}
function usrSession(userID, cords, color) {
this.UserID = userID;
this.Cords = cords;
this.Color = color;
}
usrSessionCollection = new ArrayCollection();
$.getJSON(dataurl, function (data) {
for (var x = 0; x < data.length; x++) {
usrSessionCollection.add(new usrSession(data[x].usrID.toString(), data[x].usrcords.toString() ,data[x].color.toString());
}
});
Thanks.
The biggest issue is that you have made the array private to the outside world. Only methods through which the array can be interacted with are add and empty. To be able to search the array, you need to either add that functionality in the returned object, or expose the array. Here is a modified ArrayCollection:
function ArrayCollection() {
var myArray = new Array;
return {
empty: function () {
myArray.splice(0, myArray.length);
},
add: function (myElement) {
myArray.push(myElement);
},
getAll: function() {
return myArray;
}
}
}
Now to get the last N unique session objects in usrSessionCollection, traverse the sessions array backwards. Maintain a hash of all userID's seen so far, so if a repeated userID comes along, that can be ignored. Once you've collected N such user sessions or reached the beginning of the array, return all collected sessions.
usrSessionCollection.getLast = function(n) {
var sessions = this.getAll();
var uniqueSessions = [];
var addedUserIDs = {}, session, count, userID;
for(var i = sessions.length - 1; i >= 0, uniqueSessions.length < n; i--) {
session = sessions[i];
userID = session.userID;
if(!addedUserIDs[userID]) {
uniqueSessions.push(session);
addedUserIDs[userID] = true;
}
}
return uniqueSessions;
}
I wouldn't combine the delete step with the traversal step, just to keep things simple. So here's the remove method that removes the given session from the array. Again, it's better to modify the interface returned by ArrayCollection rather than tampering with the sessions array directly.
function ArrayCollection(..) {
return {
..,
remove: function(item) {
for(var i = 0; i < myArray.length; i++) {
if(item == myArray[i]) {
return myArray.splice(i, 1);
}
}
return null;
}
};
}
Example: Get the last 10 unique sessions and delete them:
var sessions = usrSessionCollection.getLast(10);
for(var i = 0; i < sessions.length; i++) {
console.log(sessions[i].UserID); // don't need dummy variable, log directly
usrSessionCollection.remove(sessions[i]);
}
See a working example.
You made your array private, so you can't access the data, except adding a new element or removing them all. You need to make the array public, or provide a public interface to access the data. Like first(), next() or item(index).
Then you can add a search(userID) method to the usrSessionCollection, which uses this interface to go through the elements and search by userID.
UPDATE: this is how I would do it: - See it in action. (click preview)
// user session
function userSession(userID, cords, color) {
this.UserID = userID;
this.Cords = cords;
this.Color = color;
}
// a collection of user sessionions
// a decorated array basically, with
// tons of great methods available
var userSessionCollection = Array;
userSessionCollection.prototype.lastById = function( userID ) {
for ( var i = this.length; i--; ) {
if ( this[i].UserID === userID ) {
return this[i];
}
}
// NOTE: returns undefined by default
// which is good. means: no match
};
// we can have aliases for basic functions
userSessionCollection.prototype.add = Array.prototype.push;
// or make new ones
userSessionCollection.prototype.empty = function() {
return this.splice(0, this.length);
};
//////////////////////////////////////////////////////
// make a new collection
var coll = new userSessionCollection();
// put elements in (push and add are also available)
coll.add ( new userSession(134, [112, 443], "#fffff") );
coll.push( new userSession(23, [32, -32], "#fe233") );
coll.push( new userSession(324, [1, 53], "#ddddd") );
// search by id (custom method)
var search = coll.lastById(134);
if( search ) {
console.log(search.UserID);
} else {
console.log("there is no match");
}
// empty and search again
coll.empty();
search = coll.lastById(134);
if( search ) {
console.log(search.UserID);
} else {
console.log("there is no match");
}

Categories

Resources