How to create an object in javascript with illegal key name? - javascript

I like to create an object using javascript/node.js with dash in the middle of the key's name.
Here is an array that I am using today that need to convert to an object.
var data = new Array();
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah;
data['val-name'] = 'blah;
How to create an object with key like this val-name?

I've got a few spare minutes. So, code-review hat goes on.
var data = new Array();
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah;
data['val-name'] = 'blah;
Firstly, I think you have some typographic errors in this code. The last two values have oddly paired quotes.
var data = new Array();
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah';
data['val-name'] = 'blah';
Next, at the moment, you're assigning keys to an array. Which probably isn't what you mean (summary of the issue here; short version is that some collection methods will give you unexpected results). You likely mean to start an empty object as data.
var data = {};
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah';
data['val-name'] = 'blah';
Finally, you can use data literals in JS, rather than serial assignment.
var data = {
'__type': 'urn:inin.com:connection:icAuthConnectionRequestSettings',
'applicationName': 'test',
'userID': 'blah',
'password': 'blah',
'val-name': 'blah'
}
As part of this, you've created an object with a slot name that has a - in it. There's nothing illegal about this, but it does prevent you from accessing that slot with dot notation.
console> data['val-name']
'blah'
console> data.val-name
NaN
That has nothing to do with the key being illegal, and everything to do with the access being parsed as a subtraction. That is, data.val-name gets interpreted as "Subtract the value of name from the value of data.val" rather than "Access the slot val-name of the object data".

Related

Add items to a Javascript object

My app is hitting a WebAPI that returns some JSON records. I get them via jQuery AJAX and assign the JSON to a JavaScript variable. I can loop through and make changes to existing items without issue. However, how do I add more "records" to this object? I'm trying to understand the structure of the resulting variable.
Here is what I have as a test. Is this the best way?
var trustAccounts = {"accounts":[
{"entityId":12345,
"type":"IOLTA",
"nameOnAccount":"Sam Smith Trust",
"accountNumber":"987654",
"bankCode":"003",
"bankName":"Bank of Stuff",
"accountDate":"12/15/2014",
"status":"A",
"exempt":"N",
"accountId":142922,
"action":"U"}]};
var newaccount = {};
newaccount.entityId = 23456;
newaccount.type = "IOLTA";
newaccount.nameOnAccount = "John Smith Trust";
newaccount.accountNumber = "789456";
newaccount.bankCode = "003";
newaccount.bankName = "Bank of Stuff";
newaccount.accountDate = "12/15/2014";
newaccount.status = "A";
newaccount.exempt = "N";
newaccount.accountId = 142923;
newaccount.action = "U";
trustAccounts.accounts.push(newaccount);
console.log(trustAccounts);
So if we name the returned variable object we can simply create new elements using object.newItemName. Eg below:
object.newItemName = 'Hello World'
You just add them, as if they already existed. A JSON-parsed object is just a normal JavaScript object.
let obj = {};
obj.newProp = 5;
console.log(obj.newProp); // 5
obj['newProp'] = 4;
console.log(obj.newProp); // 4
You can set them in two ways, with the dot-notation or with square brackets ([]). The dot-notation way, the value after the dot is what it's called. The square bracket can accept a string or variable, so you can use it to set a property to a specific name.
If you need to nest things, you have to create each level. For example, if you wanted to set obj.something.aValue, you could do something like this:
let obj = {};
obj.something = {};
obj.something.aValue = 5;
Or, you can also do it in fewer shots, depending what you're doing:
let obj = {
something: {
aValue = 5;
}
};

How can i create object once we have values?

I am new to javascript so i dont know how to create object once we have values dynamically , so below code i have fullName and workerKey from dataItem now i want to create object selectedOwners with values of fullName and workerKey.
How can i achieve that task ?
ctrl.js
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
var fullName = dataItem.fullName;
var workerKey = dataItem.workerKey;
console.log('WORKER KEY', workerKey);
}
You use an object initializer:
selectedOwners = {
fullName: dataItem.fullName,
workerKey: dataItem.workerKey
};
The object initializer is the {...} bit. Each of those two things inside it is a property initializer. The part before the : is the name, the part after is the value, which can be the result of any expression.
In your code, you'd already created the object (var selectedItem = {};). The code above will replace that object. If you just wanted to add to it, you'd just use assignment:
selectedItem.fullName = dataItem.fullName;
selectedItem.workerKey = dataItem.workerKey;
Which you use depends on whether it matters that you not create a new object.
Edited, as per comments:
var list = [];
$scope.addProcessOwner = function(dataItem){
var selectedOwners = {"fullname":dataItem.fullName,"workerKey":dataItem.workerKey};
list.push(selectedOwners);
}
// use list to populate output
You have already created the object so all you need to do is add the values into it.
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
selectedOwners.fullName = dataItem.fullName;
selectedOwners.workerKey = dataItem.workerKey;
//This will print out the newly populated object
console.log(selectedOwners);
}

Variable as key in value pair JavaScript

Hi I am having trouble inserting my variable from controller in java script key value pair. Having real trouble reading debug in F12. Value is value but also is key and key is value.
Can't you just do: inputRegions.key = myVariable and inputRegions.Value = myVariable2 ?
Sorry if it's a stupid question.
var inputRegions = [{ parsedData.Item1 : "#FFF000" }];
or even better
var cdata = { parsedData.Item1 : "#FFF000"}
var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;
Current generally available JavaScript engines only allow static strings in object literals, thus you need temporary variables and a lot of boilerplate:
> var inputRegions = [];
undefined
> var tmp = {};
undefined
> tmp["parsedData.Item1"] = "#FFF000";
'#FFF000'
> inputRegions.push(tmp);
1
> console.log(inputRegions);
[ { 'parsedData.Item1': '#FFF000' } ]
undefined

javascript can't use input to grab an object property

So i've got this code below (all javascript). And I wish to grab the votecount for a game on user input
function Game(gamename,votes) {
this.gamename = gamename;
this.votes = votes;
};
var lol = new Game("League of Legends",1100);
var dota = new Game("DOTA 2",2100);
var ql = new Game("Quakelive",3100);
var csgo = new Game("Counter Strike: GO",4100);
function PostVotes(gnshort){
//string names - working
console.log(gnshort + 'name');
console.log(gnshort + 'votes')
var CalcVotes = function(gnshort){
var votecount = gnshort.votes;
console.log(votecount);
}
CalcVotes(gnshort);
//CalcVotes(lol); //works
};
PostVotes('lol');
I keep getting the error undefined when calling CalcVotes(gnshort). and I know it's not the function it's passing the lol as gnshort it's asif it's reading as a string instead of a variable or something. I've only been learning javascript for the past week so any advice would be helpful
PostVotes('lol'); will pass lol as a string ('lol' is equivalent to "lol"). What you need to do is simply pass the variable lol like
PostVotes(lol);
And it will return lol.votes, aka 1100.

Push to array a key name taken from variable

I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;

Categories

Resources