Assigning variables to objects in JavaScript - javascript

I am using the following method to basically create a JSON string.
var saveData = {};
saveData.a = 2;
saveData.c = 1;
However the .a and .c don't cut it for what I need to do, I need to replace these with strings. So something like..
var name = 'wibble';
saveData.name = 2;
This would get accessed with
saveData.wibble
Does anyone know how this could be achieved?

var name = "wibble";
saveData[name] = 2;
alert(saveData.wibble);
Note that, in JavaScript, the following notations are equivalent:
obj.key
obj["key"]

Use the map accessor:
var name = 'wibble'
saveData[name] = 2

You can access Javascript objects using a dictionary notation:
var name = 'wibble';
saveData[name] = 2;
saveData.wibble is now 2.

Related

How to pass dictionary inside template literal in JS

How do I pass the whole dictionary inside the template literal?
Here is my code:
var pvtInPlan = treatmentPlan.pavementIDs;
var pcrAfterPlan = treatmentPlan.pavementCondition;
var yearlyPlan = {};
pvtInPlan.forEach((key, i) => yearlyPlan[key] = pcrAfterPlan[i]); // I want to pass this yearlyPlan
var arcadeExpression = `
var plan = ${yearlyPlan};
var pvtID = 100;
return plan[pvtID]`; // I want to be able to return such statement.
Whenever I use 'var plan = ${yearlyPlan};' line, it throws me error. It works when I use 'var plan = ${yearlyPlan[100]};' directly. But I need to pass index to this dictionary from inside of template literal.
I would be glad if someone could help me with this.
Thanks!
You can just do a simple JSON.stringify if u want to dump the entire content, for example:
const yearlyPlan = JSON.stringify({ key1: 'content', key2: 'content2' })
const arcadeExpression = `
var plan = ${yearlyPlan};
var pvtID = 100;
return plan[pvtID]`; // I want to be able to return such statement.
console.log(arcadeExpression)
>>>
"var plan = {"key1":"content","key2":"content2"};
var pvtID = 100;
return plan[pvtID]"
If you want a more customized version, then u would need to access each key-value pair to format the message.

making JSON from string

I have a job to refractor strings to start using json so they can just pass json objects. So I have made array of names and then I'm trying to go through and make key and values but I'm getting an error in the console that it cant find x of no value. Can someone point me in the right direction?
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification', 'WorkQueue', 'TicketState',................ to long to post];
$().each(newName, function (key, value) {
key = newName[this];
value = newValues[this] = $('#' + key).val();
newArray = [key][value];
newArray = JSON.stringify(newArray);
alert(newArray);
$('.results').html(origArray[TicketNumber]);
});
I'm assuming you have "newValues" and "origArray" defined elsewhere?
In any case you'll need to at least adjust the following:
"$().each" should be $.each
"newArray" should be defined outside and you should use newArray[key] = value
you don't have a variable "TicketNumber" defined and so you should wrap "TicketNumber" in quotes
this is a reserved word so you shouldn't use it in "newName[this]" or "newValues[this]"
I suggest using a for loop instead of $.each() based on what you're trying to do inside.
https://msdn.microsoft.com/en-us/library/bb299886.aspx
var origArray = [];
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification'
];
for (var i = 0; i < newName.length - 1; i++) {
var object = {};
object[newName[i]] = newName[i];
object = JSON.stringify(object);
origArray.push(object);
}

Javascript create object with property as dynamic objects

I tried a lot searching and didnt get desired solutions.
What I want to achieve is
var myObject {
id1 : {
name:place_name,
location : place_loc
},
id2 : {
name:place_name,
location : place_loc
},
id3 : {
name:place_name,
location : place_loc
}
}
What I want to do is that Initially I want the properties "id1", "id2".. to be dynamic. And then dynamically assign name:place_name and other properties of each property.
I dont know the number of properties (id1,id2,id3...) hence would like to add them dynamically and following the addition of properties(id1,id2... ) I want to dynamically add the property values. (place_name & place_loc) of each id.
My code looks something like this.
var myObject = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber1].place = "SomeLoc1";
myObject[idnumber2].place = "SomePlace1";
myObject[idnumber2].place = "SomeLoc1";
But it gives error.
I know it seems simple doubt but any help would be grateful.
Thanks in advance. :)
You are trying to set a value of already assigned objects at keys "idnumber1", etc.
What you'll need is to initialize each objects for your ids like this:
var myObject = {};
myObject[idnumber1] = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber2] = {};
myObject[idnumber2].place = "SomeLoc1"
I would do it this way, it's not exactly what you did ask for, but I think it will become easier to change this later on.
function Place(name, location) {
this.name = name;
this.location = location;
}
var myObject = {}
myObject['id1'] = new Place('Foo', 'Bar');
myObject['id2'] = new Place('Internet', 'test');
console.log(myObject);
To dynamically create objects in your collection, you can use a numerical counter variable to create your object collection (myObject["id" + i] = {name: place_name, location: place_loc}).
An example:
var myObject = {};
for (i = 0; i < 20; i++){
myObject["id" + i] = {name: place_name, location: place_loc}
}
In practice, you can use a counter that you increment outside of a loop.

String from jquery array element

I'm looking at arrays in jquery and have this issue, I need to assign a key with a town name, but struggling to understand how to deal with the spaces.
var hashtable = {};
hashtable['Bognor Regis'] = ["lat=50.782998&lng=-0.673061","Sussex"];
var str = hashtable.Bognor Regis[0];
alert(str);
I thought perhaps I could do this
hashtable['Bognor-Regis'] = ["lat=50.782998&lng=-0.673061","Sussex"];
var str = hashtable.Bognor-Regis[0];
then remove the - later, but it only seems to work if i have something like this
hashtable['BognorRegis'] = ["lat=50.782998&lng=-0.673061","Sussex"];
What's the correct way of doing this ?
Thanks
If the keys have spaces you have to use the array accessor to retrieve them:
var hashtable = {};
hashtable['Bognor Regis'] = ["lat=50.782998&lng=-0.673061","Sussex"];
var str = hashtable['Bognor Regis'][0];
alert(str);
Example fiddle

Object within object add property with JavaScript

I have an object within an object. It looks like this.
var myLib = {
object1: {}
}
My basic problem is that I wanted to end up like this. So I would like to do this dynamically I will not know the property's or additional objects until run time.
var myLib = {
object1: ({"A1":({"Color":"Blue",
"height":50})
})
}
From reading here on Stack Overflow I know that I can create an object within an object by simply going like this:
myLib.Object1["A1"] = "Something"
But this does not produce what I'm looking for.
I tried this syntax which I know is wrong but basically
mylib.Object1["A1"].["color"]="Blue";
so basically here is the question. I would like to create object "A1" under "mylib.Object" and immediately add property color = "blue" to "A1". I would need to do this for several other properties, but if I can figure out how to do this for one, I can figure it out for the rest. How can I accomplish this task?
No jQuery, please. Just plain old JavaScript is what I'm looking for.**
Once I create the object and properties I would imagine I can just use a for loop to loop through the properties for that object. Like so:
for(key in mylib.Object1["A1"]){}
Right?
You can create it all from scratch like this:
var myLib = {};
myLib.object1 = {};
// assuming you get this value from your code somewhere
var x = "A1";
myLib.object1[x] = {Color: "Blue", height: 50};
Or, if all values are in variables:
var myLib = {};
myLib.object1 = {};
// assuming you get this value from your code somewhere
var x = "A1";
var colorProp = "Color";
var colorPropValue = "Blue";
var heightProp = "height";
var heightPropValue = 50;
myLib.object1[x] = {}; // create empty object so we can then add properties to it
myLib.object1[x][colorProp] = colorPropValue; // add one property
myLib.object1[x][heightProp] = heightPropValue; // add another property
These syntaxes create identical results:
myLib.object1.A1 = {};
var x = "A1";
myLib.object1[x] = {};
The first can only be used when the property name is known when you write the code and when the property name follows the proper rules for a javascript identifier. The second can be used any time, but is typically used when the property name is in a variable or when it doesn't follow the rules for a javascript identifier (like it starts with a digit).

Categories