I've get a problem with storing an array of normal js objects in parse.com.
Is it even possible?
var ObjectClass = new Parse.Object.extend("ObjectClass");
var object = new ObjectClass();
object.set("name", [{'a': 'b'}]);
object.save() - > Error 121
{"code":121,"error":"Nested keys should not contain the '$' or '.' characters."}
First things first, I believe your first line should say:
var ObjectClass = Parse.Object.extend("ObjectClass");
Without the "new" keyword, unless you're building the schema as you go, which should be fine (thanks to MongoDB), although I'm not certain.
After that, what you're doing should work if you switch your quotes from single-quotes ('') to double-quotes ("").
Related
I have a variable called uids
var uids = [];
Then I write some value to it property
uids[16778923] = "3fd6335d-b0e4-4d77-b304-d30c651ed509"
But before it
if (!uids[user.id]) {
uids[user.id] = generateKey(user);
}
This thing behaves ok. If I try to get the value of it property
uids[currentUser.id]
It will give me a value of this property. If I try to call some methods like
Object.keys(uids);
It will give me, what I expected. And here the mystery comes...
uids;
RAM rest in piece. See the node eating ram
I am very confused now. What's wrong?
This is because you are creating a huge array and node will reserve memory for it - who knows what comes. I'd say that's a scenario where you would use a Map (or a plain object, but Map feels better here.
var uids = new Map();
var key = 456464564564654;
if (! uids.has(key)) {
uids.set(key, generateKey(user))
}
You are creating an empty array (length is zero), then you assign some value to an arbitrary index. This will make the array grow as big as the index and assign the value to that index. Look at this example using node.js REPL:
> var a = []
undefined
> a[5] = "something"
'something'
> a
[ , , , , , 'something' ]
> a.length
6
Instead of creating an array, you could create a Map() or an common javascript object (singleton). Javascript objects behave like Maps but only Strings can be used as keys. If you assign a Number to be key, javascript will convert it to String automatically.
Personally, I would go with objects because they perform better. Instantiating an object takes longer than instantiating a Map (and it doesn't seem like you need to create several groups of "uids"), but once done, adding new keys and retrieving values from any key in faster when using common objects. At least that's how things go in my node.js v6.7.0 on ubuntu 14.04 but you could try for yourself. And it would also make the least alteration to your code.
var uids = {} // common/ordinary empty javascript object instead of array.
if (!uids[user.id]) { // getting value from one key works the same.
uids[user.id] = generateKey(user) // assignment works the same.
}
////
uids[16778923] = "3fd6335d-b0e4-4d77-b304-d30c651ed509" // key will be "16778923".
uids[16778923] // getting value for key "16778923" can be done using 16778923 instead of "16778923".
////
uids[currentUser.id] // still returning values like this.
Object.keys(uids) // still returning an array of keys like this. but they are all Strings.
I am building an array as an object, which a function I'm writing will eventually crawl. It's static data, so once it's populated nothing is likely to be added or removed, but I'm having difficulty formatting it properly.
The variable declaration works great if I have only one record's worth of data:
var panel = {
'url':'http://www.minorworksoflydgate.net/Testament/Clopton/nw_test_1.html',
'x':[1.63, 3.53],
'y':[6.58, 7.26],
'z':[2.05, 2.81]
}
However, if I try to add a second record's worth of information:
var panel = {'0':['url':'http://www.minorworksoflydgate.net/Testament/Clopton/sw_test_1.html',
'x':[-9.38, -7.47],
'y':[6.80, 7.49],
'z':[-8.18, -8.85]],'1':[
'url':'http://www.minorworksoflydgate.net/Testament/Clopton/nw_test_1.html',
'x':[1.63, 3.53],
'y':[6.58, 7.26],
'z':[2.05, 2.81]}
}
I get the following error: SyntaxError: Unexpected token ':'. Expected either a closing ']' or a ',' following an array element. I've tried every combination I can think of: wrapping each hunk of data in braces or square brackets and both explicitly declaring the keys and not declaring the keys. It all results in variations of this error. Where am I messing up in terms of formatting this information?
Your combining object literals and arrays in a weird way. Here is probably what you are looking for
[
{
'0':....
},
{
'1':...
}
]
This is an array of objects, where the objects can be your data records.
What I see in the code that is the problem is
[ '0': '.....'] //illegal
Square brackets represent arrays, which is a list of data whether they are strings, numbers, or objects.
[ '0', {}, 'blah', 1.2] //legal
Curly brace is the object literal or associative arrays.
{ '0': '...' }
EDITED
People say that arrays are object literals because they behave like one at run-time. You are defining array and object literals, so there are specific rules that come into play. In your code, if you instead wrote
var panel = [];
var index1 = []
panel['0'] = index1
index1['url'] = 'http://';
index1['x'] = 1.2;
var index2 = [];
index2['url'] = 'http://';
This would work, but as you can see it is a little convoluted. When you are writing an array literal, it is a list of comma separated values, and not associated keys. If you want associated keys, use curly brace.
If you want more info, search for JSON data format.
The combination of my methods of declaring an array, adding elements to the array and applying the method toString() does not work. Essentially I enter a certain number (between one and five) values to textvariables : fontVorto1, fontVorto2, fontVorto3 ……… in the html-part of the document.
When I decide on leaving the remaining textelements empty, I click on a button, to assign them to an array, by way of the following function:
function difinNombroFv () {
var fontVortoj = new array();
fontVortoj[0] = document.getElementsByName("fontVorto1")[0].value;
fontVortoj[1] = document.getElementsByName("fontVorto2")[0].value;
fontVortoj[2] = document.getElementsByName("fontVorto3")[0].value;
……………….
and put them together in a string:
x = fontVortoj.toString();
document.getElementsByName("fontVorto")[0].value = x;
(the extra variable x is not needed) to enable me sending them to the next document, where I want to unserialize them with
$fontVortoj = unserialize($_POST["fontVorto"]);
I tested the method toString() by insering an alert(x), but the result was that I got for x the value of "fontVorto1" only.
I met solutions with JSON, jQuery etc., but I never used those "languages", only HTML, JavaScript, PHP.
Will my Christmas day be spoiled because of this simple problem ;>)?
couple of things to note:
1. var fontVortoj = new array(); . here new array() is not correct. it should be:
var fontVortoj = new Array();
now if you call fontVortoj.toString(), then it will convert the array and return a string with array elements separated by comma.
you can rebuild the array from the string in php by using "explode" function.
you can rebuild the array from the string in javascript by using "split" function.
Apparently I misunderstood the question to begin with.
To serialize an astray, you can use .join()
By default, it will give you the values, joined by commas.
To deserialize, use .split()
If there's a chance that there might be commas in your values, choose a more elaborate string for joining:
var ar = ["a", "b"];
var serialized = ar.join("|"); // "a|b"
var deserialized = serialized.split("|"); //["a", "b"]
The string that you use for joining and splitting can be as long as you like.
If you want to be completely covered against any values, then you need to look at JSON.stringify() & JSON.parse(). But that had browser compatibility issues.
How would I take a string (that I got from a page using jQuery's text()) such as:
var myData = "[{name:'xxx',data:[1,2,3,4,5]},{name:'yyy',data:[5,4,3,2,1]}]"; //this is a string :(
And turn it into the actual javascript object that I need, so for example:
var myObject = [{name:'xxx',data:[1,2,3,4,5]},{name:'yyy',data:[5,4,3,2,1]}];
So 'name' and 'data' will be non-dynamic variables, however names value, the data array and the length of myObject will be dynamic.
Not really sure where to start with this one. I am guessing that I will have to do a whole lot of spliting and looping, but I am open to suggestions.
Well, it can be done very easily:
var myObject = eval(myData);
However, you should be aware of the risks of the eval function. As it runs the value as a Javascript expression, it would also run any harmful code that would be in the string, so you should only use it when you have full control over what's in the string.
If you could change the format to be JSON, you could safely parse it without risks of code injection:
var myData = '[{"name":"xxx","data":[1,2,3,4,5]},{"name":"yyy","data":[5,4,3,2,1]}]';
var myObject = $.parseJSON(myData);
You mean,
var myObject = eval('(' + myData + ')');
?
EDIT
Its major con is that you can put any javascript code (not only JSON) to eval (Chrome's F12 lets anyone to exploit this). AS you are using jQuery, best choice will be
var myObject = $.parseJSON(myData);
for cross browser compatibility.
$.parseJSON
Takes a well-formed JSON string and returns the resulting JavaScript
object. Passing in a malformed JSON string may result in an exception
being thrown. For example, the following are all malformed JSON
strings:
{test: 1} (test does not have double quotes around it).
{'test': 1} ('test' is using single quotes instead of double quotes).
I thought I knew how to declare javascript arrays but in this script I am getting an infinite loop of undefined elements in the array.
I declare three arrays of numbers, two of which have multiple values and one which has a single value.
I have a switch statement that assigns one of the three arrays to a new variable name cluster_array
When I run a for loop through cluster_array, I get an infinite loop and every element if undefined
What am I missing?
<script type="text/javascript">
var ga_west_cluster = new Array(10,11,12,14,74,75,76,77,78,79,80,81,82,83,85,86,87,88,89,90,91,92,295,296);
// original bad array
var ga_east_cluster = new Array(84);
// added an extra (dummy) value and it works fine
var ga_east_cluster = new Array(1,84);
var sc_cluster = new Array(93,94,95,96,97,98,99,100,101,102,103);
</script>
Here is the alert text:
var test_message = "cluster data\n";
for(var k=0;k<cluster_array.length;k++)
test_message += "value: "+cluster_array[k]+"\n";
Don't initialize arrays like that. Always do this instead:
var myarray = [value, value, value, ... ];
The "Array()" constructor is terribly designed. The single-argument form, when the argument is a number, is interpreted as a request to "initialize" an array with that many "empty" values. It's a pointless thing to do, so in general you're much better off using the array constant notation (as in my example above).
It doesn't seem to happen anymore in modern browsers, but I'd swear that there was a time that at least some browsers would actually allocate memory for the single-argument constructor, which was not really useful but dangerous to code that might accidentally pass in a single very large number.