jQuery Add Key Value Pair to an Empty Object - javascript

In jQuery, I can add multiple attributes to an element like so...
var input = $('<input/>').attr({ type : 'text', value : 'New Value'});
My question is, how can I achieve this using a variable like this...
var input = $('<input/>').attr(inputAttr);
I was under the assumption that inputAttr should be an object and that I could add to that object. I must be mistaken. This was one of my many attempts to make this happen.
var inputAttr = {};
inputAttr.add({ type: 'text' });
inputAttr.add({ value : 'New Value' });
I also tried like this....
var inputAttr = {};
inputAttr.add('type: text');
inputAttr.add('value : New Value');
I thought maybe inputAttr should be an array instead, which seems to output a correct string but not sure how to make it an object (which I think it should be).
var inputAttr = [];
inputAttr.push('type: text');
inputAttr.push('value : New Value');
// Then added object brackets like so
var input = $('<input/>').attr({inputAttr});
Any help would be appreciated!
Thank you in advance!

Object properties are just accessed by name. It is not an array.
var inputAttr = {};
inputAttr.type = 'text';
inputAttr.value = 'New Value';
var input = $('<input/>').attr(inputAttr);
If you want to access them indirectly via keys it is like a dictionary:
var inputAttr = {};
inputAttr["type"] = 'text';
inputAttr["value"] = 'New Value';

Key-value for object can be set in this way:
var inputAttr = {};
inputAttr.type = 'text';
inputAttr.value = 'New Value';
Fiddle.

Related

javascript - How to get the value of variable as variable with window in an object

key = 'first_name';
// This key might be anyting else
// key = 'last_name';
// key = 'age';
value = 'Ali';
// This value might be anyting else
// value = 'Jones';
// value = '50';
I want to send the value of an object using ajax like this:
key_value = {first_name: 'Ali'};
however the first_name above might change each time, so I tried:
key_value = {key: value};
however I want the value of key which is first_name in this example so I tried to use window
key_value = {window['key']: value};
But it throwed an error:
SyntaxError: missing : after property id
How can I fix this? THANKS
You can try this:
var key_value = {};
key_value[key] = value;
Snippet Example:
var key = 'first_name';
var value = 'Ali';
var key_value = {};
key_value[key] = value;
console.log(key_value);
Why not make use of shorthand property assignment in the object:
var key = 'first_name';
var value = 'abc';
var key_value = {[key]:value};
console.log(key_value);
var jsonVariable = {};
var key='first_name';
var value='Ali';
jsonVariable[key]=value;
Send jsonVariable through Ajax.

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

How to create Dictionary [Key : value] in jQuery

I have a input elements in html with two important attributes: id, and parentElementId.
I want to create a map/dictionary that looks like this: "id : parentElementId".
var parent = $(".people-autocomplete").map( function(){ return $(this).attr('id')+':'+$(this).attr('parent'); }).get() ;
for know I'm putting the values into a string, which I parse later on in the code. I presume there is a more elegant solution than this.
Use an object:
var obj = {};
$(".people-autocomplete").each(function() {
obj[$(this).attr('id')] = $(this).attr('parent');
});
You can then access the parent of a specific id:
var parent = obj.idName;
or through a string:
var idStr = 'idName';
var parent = obj[idStr];
And you can loop through:
for (idStr in obj) {
var parent = obj[idStr];
}
You can use JSON object for this purpose, You are confusing the usage of .map() in Jquery with map of other languages.
You can create a Json object like,
var xObj = {};
xObj.id = 'parentElemtnId';
alert(JSON.stringify(xObj)); // { id : 'parentElementId' }

Passing a variable inside a variable in javascript

I am trying to create a variable that will include another variable.
Example:
var options_id = ...
where 'id' is created dynamically through another variable so that the result could be
var options_1 = ...
var options_2 = ...
etc.
The 'id' is declared dynamically like this:
var id = itemid;
What would be the syntax to include the 'id' variable in the variable
var options_id
?
I suppose this is what your looking for:
window['options_' + id] = ...
Have you thought about using an object instead? You could do:
var id = itemid;
var options = {};
options['id'] = …;
Then access it using:
options.id
I think, that there is an Object in JS for that purpose.
For example:
var options = new Object();
var options.id = 'foo';
or if you want to use numeric indices then you can resort to Array

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