I am building some UI page using jQuery. In some function, i am creating a JavaScript object as
var key = "04:52:00";
var val = 13.21;
var data = {
key : val
};
When I try to loop through the data object like,
for(var category in data) {
alert(category);
var points = data[category];
alert(points);
}
In the above, I am getting the value of val variable correctly as 13.21, but I am not getting key variable value, instead in the alert(category);, I am getting key not 04:52:00.
I am not much familiar with jQuery/JavaScript.
You have to use bracket notation to use variables as keys, when using dot notation or when creating an object, the key doesn't have to be quoted, and the literal string will be used as a key instead of the variable.
var key = "04:52:00";
var val = 13.21;
var data = {};
data[key] = val;
When initializing an object using a literal, like you're doing, you can't use variables for keys.
You'll have to use the bracket notation instead:
var data = {};
data[key] = val;
Related
Trying to return all key values of givenName but it gets nothing.
I"m new to this is...
window.location.href = 'gonative://contacts/getAll?callback=contacts_callback';
function contacts_callback(data) {
var obj = JSON.stringify(data);
var obj = JSON.parse(obj);
var givenName = obj.contacts[0].givenName;
var keys = Object.keys(obj.contacts.givenName);
document.getElementById("demo").innerHTML = keys;
}
assuming obj.contacts is an array of objects, each having a givenName property
Since obj.contacts is an array, it is unlikely to have a givenName property itself (it could, but then you wouldn't be getting that through JSON)
var keys = Object.keys(obj.contacts.givenName);
is same as
var keys = Object.keys(undefined);
and you should be getting an error in the browser developer tools console at this point
You'll want to use Array#map function as follows
function contacts_callback(obj) {
var givenNames = obj.contacts.map(({givenName}) => givenName);
document.getElementById("demo").innerHTML = givenNames;
}
Note
function contacts_callback(data) {
var obj = JSON.stringify(data);
var obj = JSON.parse(obj);
besides the obvious error (doesn't bother javascript though) of declaring the same variable twice (obj), the code is identical to:
function contacts_callback(obj) {
Note: however, that if the code inside the function were to mutate any values in obj, then, the original code should be used if you do not want to make changes to the passed in object
I have a variable var key = "Something" and want to set a document using this variable as the key.
When I'm trying to do it using settings_ref.update({key: false}); this is obviously using "key" as a string itself.
How can I use a variable as the key of the new data?
You should use the bracket notation:
var obj = {};
obj[key] = false;
settings_ref.update(obj);
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
Let's take an example in javascript
var b = function(){
var key = {};
var result = [];
var a =
[{people: "people1"},
{people: "people2"},
{people: "people2"},
{people: "people3"}]
for(i=0;i<a.length;i++)
{
var val = a[i][people];
if(angular.isUndefined(key[val]))
{
Key[val] = "abc"; /////This line is foreign to my knowledge.
result.push(val);
}
}
return result;
}
Now in this Example i am creating an object Key and a array result.
The for loop will loop through the a variable and store the value of people property in the var val.
The angular.Isundefined function check whether the key[val] contains any duplicate data if not then it will add using the
Key[val] = "abc".
1) Now i have no idea how this line is creating the value and key pair in the key object.
2) Please tell me other ways to add value to the object.
O/P is as follows
key = Object {people1: abc, people2: abc, people3: abc}
hence it is adding value to key object without duplicating the value.
P.S. it is just an example not the real code.
From the link of Andreas in comments
I think this solves my problem.
the other way to add the key and value to the JSON object is like this.
obj = {};
obj[people1] = "data";
obj[people2] = "data";
obj[people3] = "data";
console.log(obj);
The key cannot be same but the value can be same.
So this is what my question was
Key[val] = "abc";
this line is getting the val variable dynamically and adding the val variable as the key and the value is abc.
Twist:
Do you think that
key.val = "abc";
work?
No:
This is what provided by the site
Any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number)
can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
in the following example i add count in my json my json come from ajax but i want to add count so add count below code that's work fine for me here .count is my custom value added by me, it is not part of my response
$scope.data = response.items;
for (var i = 0; i < response.items.length; i++) {
response.items[i].count = i;
}
I want to create an object some thing like this
var key = "key";
var obj={};
obj[key] = "value";
My required output is
{ "key":"valie"}
Key type must be string because i have keys like #12:5 , #12:89 ( orientDB ids ).
REASON:-
Because embeddedList of orientDB is not accepting any key without quotes.
Thanks
You're probably looking for JSON syntax.
Here's output from my console.
var key = "key"; //var not Var
var obj={}; //same here
obj[key] = "value";
"value"
obj
Object {key: "value"} //key is not in quotes, need to stringify!
JSON.stringify(obj);
"{"key":"value"}"
Object literals in javascript can be declared with quoted keys:
{
"Okeli-dokeli": "Flanders",
"Doh!": "Simpson!"
}
You can also dynamically assign values to a key in javascript with the bracket syntax:
var x = {};
x["A B C"] = "foo";
ADDED:
The JSON format is based on a subset of javascript but has object keys which are always quoted. Therefore converting any javascript object to JSON will "stringify" the keys:
> JSON.stringify( { a : 'b' } )
> "{"a":"b"}"
In the off chance you are not expecting nested objects, this can easily work as well:
var key = "key";
var obj={};
obj[key] = "value";
var s = "{\r\n";
for (var p in obj) s+= ' "'+p+'": "' + obj[p] + '"\r\n';
s += "}\r\n";
Also, it's var, not Var (no capital first letter).
I need to store an object in localStorage - and I know that in order to do so, I have to convert the object into a string. All cool.
My problem is in actually creating the object in the first place: I have two values in sessionStorage that need to be added to the object which is then passed into localStorage. However, when I try to create the object, one value is being stored as the variable name rather than its (numeric) value. Any idea whats going on here?
var siteName = sessionStorage['1'];
var siteID = (+sessionStorage['2']);
var temp = {siteID:siteName};
alert(typeof siteID);
alert(JSON.stringify(temp));
The first alert confirms that siteID is indeed a number type, but the second alert shows that the variable name (siteID) is stored rather than its numeric value.
This line:
var temp = {siteID:siteName};
...creates an object containing a property called siteId with the value taken from the siteName variable.
If you want the property name to be taken from the siteID variable instead:
var temp = {};
temp[siteID] = siteName;
Or in ES2015 (aka "ES6") you could use the new computed property name syntax:
// ES2015+ only!
var temp = {[siteId]: siteName};
In JavaScript, you can access/create properties on objects in two different but equal ways: Using dotted notation with a literal property name:
obj.foo = "bar"; // Creates a `foo` property on `obj` with the value `"bar"`
...or using bracketed notation and a string:
obj["foo"] = "bar"; // Does the same thing
The keys in object initializers like your var temp = {siteID:siteName}; are always used literally (although they can optionally be in quotes); there's no way with an object initializer to have a key taken from a variable instead. So you have to do it as a two-step process, first create the object, then set the property.
So, if you do
temp[siteID] = siteName;
...the number in siteID will be converted to a string and will become the property name, with the value of siteName being the value.
var temp = {};
var key = 1;
temp[key] = "value";
console.log(temp[1]); // "value"
console.log(temp["1"]); // "value"
(Property names are always strings in JavaScript [for now].)
Change it to this.
var temp = {};
temp[siteName] = siteID;
Or if the typeof test was meant to show the property name, you'd reverse them.
var temp = {};
temp[siteID] = siteName;
But be aware that siteID is considered a String from that point forward.