I want to make Javascript object dynamic - javascript

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"}

Related

How to convert a string to a template string

Let's say I have:
var json = '{"greetings": "`${greetings}`"}';
var obj = JSON.parse(json);
var template = obj.greetings; //`${greetings}`
var greetings = 'hello';
how to evaluate template to get hello ?
Since JSON.parse() returns obj.greetings as string, you can use eval() to run the string as js. So just:
var json = '{"greetings": "`${greetings}`"}';
var obj = JSON.parse(json);
var template = eval(obj.greetings); //`${greetings}`
var greetings = 'hello';
console.log(greetings)// hello
But eval() should always be used with caution as string maybe entered through user input.
Edit:
The above code with eval returns undefined.
This is because JavaScript Hoisting doesn't work for initialized variable.
So we surely need to move the initialisation var greetings = 'hello'; at the top.
Solution without eval():
Apply template string to the whole string.
var greetings = 'hello';
var json = `{"greetings": "${greetings}"}`;
var obj = JSON.parse(json);
var template = obj.greetings; //`${greetings}`
console.log(template); //hello

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);

Set variable value as key in backbone.js

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;

JavaScript inset variable into brackets

when I alert btnName it is not fetching the attr name and instead using the text btnName.
var btnName = orderBtn.attr("name");
var obj = {btnName:true,json:1};
I am sure this is possible, I just can;t figure it out.
You need to write it like this:
var obj = {json: 1}
obj[orderBtn.attr('name')] = true
There's no way to include an expression (such as a variable) as a key when constructing an object using literal notation.
var obj = {foo: 'bar'}
is essentially shorthand for
var obj = {'foo': 'bar'}
If you want to refer to a variable foo, you need square bracket notation:
var obj = {}
obj[foo] = 'bar'
var btnName = orderBtn.attr ("name");
var obj = { json: 1 };
obj [btnName] = true;
Use brackets if you want to use a variable as a key:
var obj = { json: 1 };
obj[btnName] = true;

JavaScript Object/Array access question

Set an object, with some data.
var blah = {};
blah._a = {};
blah._a._something = '123';
Then wish to try and access, how would I go about doing this correctly?
var anItem = 'a';
console.log(blah._[anItem]);
console.log(blah._[anItem]._something);
The bracket notation should look like this:
var anItem = 'a';
console.log(_glw['_'+anItem]);
console.log(_glw['_'+anItem]._something);
You can test it here (note that I replaced _glw with blah in the demo to match the original object).
Not sure I understand the question, but here are some basics.
var foo = {};
// These two statements do the same thing
foo.bar = 'a';
foo['bar'] = 'a';
// So if you need to dynamically access a property
var property = 'bar';
console.log(foo[property]);
var obj = {};
obj.anotherObj = {};
obj.anotherObj._property = 1;
var item = '_property';
// the following lines produces the same output
console.log(obj.anotherObj[item]);
console.log(obj.anotherObj['_property']);
console.log(obj.anotherObj._property);

Categories

Resources