Set variable value as key in backbone.js - javascript

I couldn't add the variable value as my key name in backbone.js is there any way to do this ?? look at the code below
(function ($) {
Today = Backbone.Model.extend({
});
var data= ['a','b','c'];
for(var i=0;i<data.length;i++){
today.set({i:data[i]});
}
} (jQuery));
how i am able to do that ?

You should be able to simply pass data to today.set().
var data = ['a','b','c'];
var today = new Today();
today.set(data);
console.log(today.attributes);
// {0: "a", 1: "b", 2: "c"}
Though, to explain the problem: Identifiers on the left-hand of : in Object literals always become the key's name themselves. To use a variable's value as a key, you have to use bracket member operators.
var tmp = {};
tmp[i] = data[i];
today.set(tmp);

So in javascript an object literal with unquoted key uses the string version of that key:
var i=1;
var obj = {i: "this sets obj.i to this string, not obj['1']"};
If you want a computed key, follow this pattern:
var keyname = i + 'whatever' + 42;
var obj = {};
obj[keyname] = value;

Related

Use variable as property JavaScript [duplicate]

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = "happyCount";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?
Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
You need to make the object first, then use [] to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";
var person = {[key]:"John"};
console.log(person); // should print Object { name="John"}
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also
supports computed property names. That allows you to put an expression
in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
Use this.
var key = 'a'
var val = 'b'
console.log({[key]:val})
//a:'b'
In ES6 We can write objects like this
const key= "Name";
const values = "RJK"
const obj = {
[key]: values,
}
In TypeScript, it should look something like this
let title ="Current User";
type User = {
[key:string | number | symbol]: any
};
let myVar: User = {};
myVar[ title ] = "App Developer";
console.log(myVar)// Prints: { Current User:"App Developer"}
let key = "name";
let name= "john";
const obj ={
id:01
}
obj[key] = name;
console.log(obj); // output will {id:01,name:"john}
Use square brackets shown it will set as key
The Reality
The problem in JS is simply that:
{ x: 2 }
is THE SAME as:
{ "x": 2 }
(even if you have x a variable defined!)
Solution
Add square brackets [] around the identifier of the key:
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
(Nowadays the keyword var is not much used, so please use instead const or let)
tldr;

I want to make Javascript object dynamic

Here is Code
var str = "Value1";
var str1 = "Value2";
var obj = {
[str]: str1
};
console.log(obj);
I am getting obj as
{
Value1:"Value2"
}
But I want this object as
{
"Value1":"Value 2"
}
Can any one explain how it is possible?
At first your code: var obj = {["Value1"]: "Value2"}; is wrong. You have to write:
var obj = {"Value1": "Value2"}; or var obj = {Value1: "Value2"};.
And then if I understood you correctly: in your comment you wrote:
I wana get Value1 in double quotes too dynamic means I want dynamic index too in double quotes
The answer:
Object {Value1:"Value2"} is the same like {"Value1":"Value2"}. The difference is to see in displaying (spelling, writing) of your code only.
For example you will not see the difference if you execute following code:
var myObj1 = {"Value1":"Value2"};
var myObj2 = {Value1:"Value2"};
console.log(myObj1.Value1); //Value2
console.log(myObj2.Value1); //Value2
console.log(myObj1["Value1"]); //Value2
console.log(myObj2["Value1"]); //Value2
console.log(JSON.stringify(myObj1)); //{"Value1":"Value2"}
console.log(JSON.stringify(myObj2)); //{"Value1":"Value2"}

str.split to json with names

I have taken a string that is "title:artist" and used str.split :
res = song.split(":");
Which gives me an output of :
["Ruby","Kaiser Chiefs"]
I was wondering how I could add name to this so that it appears as :
["name":"Ruby", "artist":"Kaiser Chiefs"]
var res = song.split(':');
var jsonString = JSON.stringify({ name: res[0], artist: res[1] });
You can find more information about how to use JSON.stringify here but basically what it does is takes a JavaScript object (see how I'm passing the data as an object in my answer) and serializes it into a JSON string.
Be aware that the output is not exactly as you have described in your question. What you have is both invalid JavaScript and invalid JSON. The output that I have provided will look more along the lines of {"name":"Ruby", "artist":"Kaiser Chiefs"}. Notice how there is {} instead of [].
["name":"Ruby", "artist":"Kaiser Chiefs"] isn't a valid format I guess you want to create an object so you could use just the split like :
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {'name': my_string_arr[0],"artist": my_string_arr[1]};
console.log(my_object);
Or also assign the values to the attributes separately like:
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {};
my_object.name = my_string_arr[0];
my_object.artist = my_string_arr[1];
console.log(my_object);
Hope this helps.
What you're looking for is: Object. Here is how you do it:
var str = "Ruby:Kaiser Chiefs";
var res = str.split(':');
// this is how to declare an object
var myObj = {};
// this is one way to assigne to an object
// using: myObj["key"] = value;
myObj["name"] = res[0];
// this is another way to assign to an object
// using: myObj.key = value;
myObj.artist = res[1];
console.log(myObj);

accessing JSON value if key is array element

suppose i receive JSON object from the server as this
{ "asdf[zxcv]": "qwer" }
how do i access asdf, zxcv, and qwer in javascript, so i can use the object this way ?
theobj.asdf[zxcv] = 'qwer'
Bracket notation is not in the JSON RFC. You can only read it as string.
var simpleObj = {
"simpleKey": "simpleValue"
}
console.log(simpleObj)
var advObj = {
"advKey[1]": "advValue"
}
console.log(JSON.parse(advObj)); // SyntaxError
console.log(advObj.advKey[1]) // TypeError
console.log(advObj["advKey[1]"]) // can only read as string
You would need to refactor the source JSON into something more meaningful so you can access the values in regular JavaScript way.
Run the following snippet to check how you can solve the issue:
var x = '{ "asdf[zxcv]": "qwer" }';
var y = JSON.parse(x);
var result = Object.keys(y).reduce(function(result, key) {
var parentKey = key.substring(0, key.indexOf("["));
var innerKey = /[a-z]+\[([a-z]+)\]/i.exec(key)[1];
if (!result.hasOwnProperty(key))
result[parentKey] = {};
result[parentKey][innerKey] = y[key];
return result;
}, {});
document.getElementById("structure").textContent = JSON.stringify(result);
var zxcv = result["asdf"]["zxcv"];
document.getElementById("someValue").textContent = zxcv;
<h2>Refactored data structure as nested objects:</h2>
<div id="structure"></div>
<h2>Accessing some value: result["asdf"]["zxcv"] or result.asdf.zxcv</h2>
<div id="someValue"></div>
It's all about creating nested objects to represent the associative keys in the source JSON properties representing a conceptual associative array...
This is one of the way to access all elements without reconstructing object.
jQuery.each(JSON.parse('{ "asdf[zxcv]": "qwer" }'), function(index, value) {
var i = index;// i = "asdf[zxcv]"
var v = value;// v = "qwer"
var iOfInnerValue = (/\[(.*?)\]/g).exec(i)[1];// innerValue = "zxcv"
var iOfOuterValue = index.replace("["+(/\[(.*?)\]/g).exec(i)[1]+"]",""); // outerValue = "asdf"
});
You'll need to assign the data to a variable and then you can use Object keys to get the key which is the part before the :. Here's an example.
var j = { "asdf[zxcv]": "qwer" };
console.log(Object.keys(j)); //["asdf[zxcv]"]
console.log(j); //{asdf[zxcv]: "qwer"}

How to get value in an object's key using a variable referencing that key?

I have an object and I can reference key a as in the following:
var obj = {
a: "A",
b: "B",
c: "C"
}
console.log(obj.a); // return string : A
I want to get the value by using a variable to reference the object key as below:
var name = "a";
console.log(obj.name) // this prints undefined, but I want it to print "A"
How can I do this?
Use [] notation for string representations of properties:
console.log(obj[name]);
Otherwise it's looking for the "name" property, rather than the "a" property.
obj["a"] is equivalent to obj.a
so use obj[name] you get "A"
Use this syntax:
obj[name]
Note that obj.x is the same as obj["x"] for all valid JS identifiers, but the latter form accepts all string as keys (not just valid identifiers).
obj["Hey, this is ... neat?"] = 42
You can get value of key like these ways...
var obj = {
a: "A",
b: "B",
c: "C"
};
console.log(obj.a);
console.log(obj['a']);
name = "a";
console.log(obj[name])
I use the following syntax:
objTest = {"error": true, "message": "test message"};
get error:
var name = "error"
console.log(objTest[name]);
get message:
name = "message"
console.log(objTest[name]);
productList = {
"name": "Title"
}
var key = "name";
console.log(productList[key])
productList is an arbitraty object with only one key. the key variable holds the same key as a string.
Using the [] you can access the value dynamically.
https://jsfiddle.net/sudheernunna/tug98nfm/1/
var days = {};
days["monday"] = true;
days["tuesday"] = true;
days["wednesday"] = false;
days["thursday"] = true;
days["friday"] = false;
days["saturday"] = true;
days["sunday"] = false;
var userfalse=0,usertrue=0;
for(value in days)
{
if(days[value]){
usertrue++;
}else{
userfalse++;
}
console.log(days[value]);
}
alert("false",userfalse);
alert("true",usertrue);
var o = { cat : "meow", dog : "woof"};
var x = Object.keys(o);
for (i=0; i<x.length; i++) {
console.log(o[x[i]]);
}
IAB
fyi, if the type of the object is not known it's a little trickier:
var name = "a";
console.log(obj[name as keyof typeof obj]);
(refer to this post)

Categories

Resources