Access parent from child within array using Parse.com - javascript

I have a Game class and a Roundclass. Game has a column named rounds which is an array of Round objects.
As there is a small and limited amount of them I chose Array over Parse.Relation, which I consider easy to use.
I have a Round object and I want to access the Gamewhich is his parent object.
How do I achieve that ?

If you're using the javascript API, I would use the Parse.Query.containsAll method.
This method takes two parameters, the key (field name) that must contain the object(s), and an array of values (in this case, the array will only contain one value.
var gameQuery = new Parse.Query("Game");
gameQuery.containsAll("rounds", [ round ]);
gameQuery.first().then
(
function( game )
{
//do stuff
}
);
I've never actually used this method for an array of pointers, though. you may need to pass an array containing just the object id of the round, rather than the pointer to the round. I'm not sure.

Related

Create an indefinite number of data structures based on number of DOM elements retrieved with jQuery

I'd like to instantiate an indefinite number of javascript array, relying on the number of elements retrieved with jQuery.
dogHouse = {};
var dogs = $('.dogs'); // admit that dogs.length = 2
Now, I'd like to use each loop (or something else) to instantiate (in this case) two arrays definited in dogHouse or in window, each with his own name.
dogs.each( function(){
});
Is this possible?

JavaScript - Storing objects with unique key ?

I have an JavaScript object which is being pushed to a global object.
var storedElement = {
element: currentElement,
parentElement: parentElement,
elementChild: currentChild
}
storedElement is being pushed to a global array called.
pastLocations = []
I'm essentially trying to keep a history of the locations an element has been to. To do this I'm wanting to store these properties into the global array. If the same element already exists and has the same parent in the global then I dont want to push, but if the parent is different then push.
Is there a way I can put a unique key with item so I quickly and effectively get access to this element in the object. At the moment I currently have several for each loops to get the data from the object but this inst a practical approach. As Ideally I want 1 function to push to the global and to retrieve an element.
If I was to provide a unique keys for each object, how would I would know what key it is based of just knowing the element ?
In Javascript, an array [...] stores sequential values, preserving their order, and provides fast access if you know the index.
An object or dictionary {...} stores values along with a key, without preserving their order, and provides fast access if you know the key.
If you only need to store elements with distinct 'parent', you can use an object, using the parent as key. If you also need to browse them in order, your best bet is to use both an array and an object:
storedElements = []
storedByParent = {}
What you store in each depends on your application requirements. You may store a copy of the object:
newEl = {element: ..., parent: parentElement, ...}
storedElements.push(newEl)
storedByParent[parentElement] = newEl
Or you may store an index into the array:
storedElements.push(newEl)
storedByParent[parentElement] = storedElements.length - 1
Or you may store a simple boolean value, to just keep track of which parents you have seen:
storedElements.push(newEl)
storedByParent[parentElement] = true
This latter use of an object is usually known as 'set', because it's similar to the mathematical object: even if you call mySet[12] = true a hundred times, the set either contains the element 12, or it does not.

Json length is always undefined in node js

I am trying to iterate simple json array, but it always return the length of the array is undefined.
var chatmessage = {};
...................
...................
socket.on('listmessage', function(mesg){
chatmessage={"message":"Hello", "to":"sjdfjhsdf"};
});
socket.on('private', function(mesg){
console.log(chatmessage.length+' - '+chatmessage.message +' - '+ chatmessage.to);
});
when private event get trigger it returns
undefined - Hello - sjdfjhsdf
I think it consider length key word as a json array key like {"length":40}.
I have tried Object.keys(chatmessage).length but it returns the total number key value(2) but I have only one record.
What is the right way to iterate json in node js
I am trying to iterate simple json array
Two issues there:
That's not JSON. JSON is a textual notation for data exchange. If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. It's a JavaScript object initializer.
It doesn't define an array, it defines an object.
Objects don't have a length property. If you want your chatmessage to say how many properties it has, you'll have to add a third property explicitly (which then raises the question of whether the value should be 2 or 3 :-) ). Or alternately, you could make it an array of objects with "key" and "value" properties, but that would be awkward to work with.
If you need to, you can determine how many properties an object has in a couple of ways:
Object.keys(obj).length will tell you how many own, enumerable properties the object has (ignoring any with Symbol names, if you're using ES2015). The number will not include any inherited properties or any non-enumerable properties. The answer in your example would be 2.
Object.getOwnPropertyNames(obj).length) will tell you how many own properties the object, has regardless of whether they're enumerable (but again ignoring any with Symbol names). The number will not include any inherited properties or any non-enumerable properties. The answer in your example would again be 2 as your object has no non-enumerable properties.
I have tried Object.keys(chatmessage).length but it returns the total number key value(2) but I have only one record.
As I said above, Object.keys will tell you how many own enumerable properties the object has. If you're trying to find out how many objects there are, the answer is 1.
If your goal is to send an array of chat messages, then you want to create that like this:
var chatmessages = [
{"message":"Hello", "to":"sjdfjhsdf"}
];
That defines an array with one entry: A single object representing a chat message. Multiple ones would be separated with ,:
var chatmessages = [
{"message":"Hello", "to":"sjdfjhsdf"}, // First message
{"message":"Hello again", "to":"sjdfjhsdf"} // Second message
];
Note that if you're doing that, your verb should probably be listmessages (plural), not listmessage. (I mention this in case your native language handles plurals differently from English; there are a lot of different ways plurals are handled in the various human languages around the planet. :-) )

Creating multi-dimensional arrays in javascript, error in custom function

I was trying to define an array (including other arrays as values) in a single javascript statement, that I can loop through to validate a form on submission.
The function I wrote to (try to) create inline arrays follows:
function arr(){
var inc;
var tempa = new Array(Math.round(arguments.length/2));
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
This is called three times here to assign an array:
window.validArr = arr(
'f-county',arr('maxlen',10, 'minlen',1),
'f-postcode',arr('maxlen',8, 'minlen',6)
);
However in the javascript debugger the variable is empty, and the arr() function is not returning anything. Does anyone know why my expectations on what this code should do are incorrect?
(I have worked out how to create the array without this function, but I'm curious why this code doesn't work (I thought I understood javascript better than this).)
Well from what your code does, you're not really making arrays. In JavaScript, the thing that makes arrays special is the management of the numerically indexed properties. Otherwise they're just objects, so they can have other properties too, but if you're not using arrays as arrays you might as well just use objects:
function arr(){
var inc;
var tempa = {};
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
What you're seeing from the debugger is the result of it attempting to show you your array as a real array should be shown: that is, its numerically indexed properties. If you call your "arr()" function as is and then look at (from your example) the "f-county" property of the result, you'll see something there.
Also, if you do find yourself wanting a real array, there's absolutely no point in initializing them to a particular size. Just create a new array with []:
var tempa = [];
Your code works. Just inspect your variable, and you will see that the array has the custom keys on it. If not expanded, your debugger shows you just the (numerical) indixed values in short syntax - none for you.
But, you may need to understand the difference between Arrays and Objects. An Object is just key-value-pairs (you could call it a "map"), and its prototype. An Array is a special type of object. It has special prototype methods, a length functionality and a different approach: to store index-value-pairs (even though indexes are still keys). So, you shouldn't use an Array as an associative array.
Therefore, their literal syntax differs:
var array = ["indexed with key 0", "indexed with key 1", ...];
var object = {"custom":"keyed as 'custom'", "another":"string", ...};
// but you still can add keys to array objects:
array.custom = "keyed as 'custom'";

Accessing Nested Objects in Json

I have a custom object which contains other items (ie arrays, strings, other types of objects).
I am not sure how to traverse the object to iterate and list all of the object types, keys, and values of the nested items.
Second to this issue I don't know how many levels of nesting there are (as the object is generated dynamically from the back-end and passed to me as one object).
Any ideas (and should I just use javascript/jQuery or both to do this most efficiently)?
Thanks I'll give the code a go. I am retrieving a result set from a webservice which returns a different set of columns (of differing datatypes) and rows each time. I don't know the names of the columns which is why I am trying to get the data however I can.
Depending on the datatype I will perform a different action (sum the amount, format it etc).
JSON-serialized objects contain a hierarchy, w/o any reference cycles, so it should be fairly straightforward to traverse, something like
function visit(JSONobj, f)
{
for (var key in JSONobj)
{
var value = JSONobj[key];
f(key,value);
if (value instanceof Object)
visit(value, f);
}
}
where f is a function that does something with keys and values. (of course you could just write a function to do this directly).
What exactly are you trying to find within the object?

Categories