How to create Dictionary [Key : value] in jQuery - javascript

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

Related

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

Merging objects in jQuery

Fiddle Example.
$('#send').click(function(){
var object = {};
var chat = {};
chat = {msg:$('#message').val()};
var pic = $('.pic');
object = pic.map(function(){
var src = $(this).attr('src'),
tid = $(this).data('id'),
title = $(this).attr('title');
return {src:src,tid:tid,title:title}
}).get();
var newobj = $.extend(chat,object);
console.log(JSON.stringify(newobj));
});
The code combines two objects chat and object into one single object. This is how it looks like after JSON.stringify
{"0":{"src":"pic.jpg","tid":3,"title":"logo"},
"1":{"src":"pic2.jpg","tid":3,"title":"logo2"},
"msg":"dfdfdf"
}
Is it possible to merge the objects into this:
{
"0":{"msg":"dfdfdf"},
"1":{"src":"pic.jpg","tid":3,"title":"logo"},
"2":{"src":"pic2.jpg","tid":3,"title":"logo2"}
}
I have tried chat[0] = {msg:$('#message').val()}; and map function but it doesn't even merge the chat object into the object object.
HTML:
<div class="area">
<button>Choose Picture</button>
</div>
You could delete and reinsert it
var newobj = $.extend(chat,object);
delete newobj.msg; // delete the property
newobj["0"] = chat; // add the property
console.log(JSON.stringify(newobj));
And since you're using Numbers as the property names or identifiers, it would be better suited if it were an Array instead of an Object.

creating nested array javascript

Have looked at many examples but cant seem to get to make an nested array to store some data nicely. How can I get the following code to work? It gives me an error now:
var shipdata = [];
shipdata['header']['bedrijfsnaam'] = $('[name="bedrijfsnaam"]').val();
shipdata['header']['naam'] = $('[name="naam"]').val();
shipdata['header']['straat'] = $('[name="straat"]').val();
shipdata['header']['postcode'] = $('[name="postcode"]').val();
shipdata['header']['plaats'] = $('[name="plaats"]').val();
shipdata['header']['telefoon'] = $('[name="telefoon"]').val();
shipdata['header']['email'] = $('[name="email"]').val();
shipdata['header']['instructies'] = $('[name="instructies"]').val();
shipdata['header']['ordernummertje'] = $('[name="ordernummertje"]').val();
$(".pakketten").each(function(index, element) {
index++;
shipdata['pakketten']['pakket'+index]['lengte'] = $('[name="lengte'+index+'"]').val(),
shipdata['pakketten']['pakket'+index]['breedte'] = $('[name="breedte'+index+'"]').val(),
shipdata['pakketten']['pakket'+index]['hoogte'] = $('[name="hoogte'+index+'"]').val(),
shipdata['pakketten']['pakket'+index]['gewicht'] $('[name="gewicht'+index+'"]').val()
});
Probably im doing this all wrong, but some pointers would be welcome.
Thanks!
First of all, you are creating an object and not an array, so use {} instead of [] for the main container.
Second, when inserting multiple values at the same time, you can use a much more compact notation:
var shipdata = {
'header': {
'bedrijfsnaam': $('[name="bedrijfsnaam"]').val(),
'naam': $('[name="naam"]').val()
'...': '...'
},
'pakketten': []
};
$(".pakketten").each(function(index, element) {
shipdata['pakketten'].push({
'lengte': $('[name="lengte'+index+'"]').val(),
'breedte': $('[name="breedte'+index+'"]').val(),
'...': '...'
});
});
Besides, anytime you want to access an object or array in any way, you have to initialize it beforehand as already mentioned by #antyrat.
You need to create objects each time you want to have nested array:
var shipdata = {};
shipdata['header'] = {};
shipdata['header']['bedrijfsnaam'] = $('[name="bedrijfsnaam"]').val();
//...
shipdata['pakketten'] = {};
$(".pakketten").each(function(index, element) {
index++;
shipdata['pakketten']['pakket'+index] = {};
shipdata['pakketten']['pakket'+index]['lengte'] = $('[name="lengte'+index+'"]').val(),
// ...
Answer updated due to comments as arrays didn't have string indexes.

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