Merging objects in jQuery - javascript

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.

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

Javascript & jQuery push array to object based on custom attribute

Problem
There are a couple of HTML tags with classes as follows
<span class=​"keyword" column-name=​"Product Group">​Outdoors</span>​
<span class=​"keyword" column-name=​"Material Code">​10001003​</span>​
<span class=​"keyword" column-name=​"Material Code">​10001000​</span>​
All the span needs to be iterated through and a new object would be created with the column-name attribute as its property and the relevant text passed into an array.
Code So Far
I am using the below code but the array passed consists of all the text from the span
var searchCriteria = {};
var keyword = [];
$('.keyword').each(function(index, elem) {
col = $(elem).attr('column-name');
keyword.push($(elem).text());
searchCriteria[col] = (keyword);
});
console.log(searchCriteria);
The above code prepares the object as
{
Material Code: ['Outdoors', '10001003', '10001000']
Product Group: ['Outdoors', '10001003', '10001000']
}
Result Expected
The result of the object which I am expecting is
{
Material Code: ['10001003', '10001000']
Product Group: ['Outdoors']
}
JS Fiddle
Here is a JSFiddle of the same - http://jsfiddle.net/illuminatus/0g0uau4v/2/
Would appreciate any help!
When you use searchCriteria[col] = (keyword);, it does not copy the keyword array. It just stores pointer to that array. So, if you update keyword after assigning it to some variable, it'll also get updated as both of them points to the same array. If you want to copy array you may use .slice() on array. But here it is not needed.
Use the following code instead
var searchCriteria = {};
$('.keyword').each(function(index, elem) {
col = $(elem).attr('column-name');
if ( !Array.isArray(searchCriteria[col]) )
searchCriteria[col] = [];
searchCriteria[col].push($(elem).text());
});
console.log(searchCriteria);
http://jsfiddle.net/0g0uau4v/3/
You can't use the same array as the value for each column. Instead, create a new array each time you encounter a new column, or simply append the value to the existing array if the column-name already exists:
$(function() {
var searchCriteria = {};
$('.keyword').each(function(index, elem) {
var col = $(elem).attr('column-name');
var keyword = searchCriteria[col] ? searchCriteria[col] : [];
keyword.push($(elem).text());
searchCriteria[col] = (keyword);
});
$("#result").text("Result: " + JSON.stringify(searchCriteria));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="keyword" column-name="Product Group">Outdoors</span>
<span class="keyword" column-name="Material Code">10001003</span>
<span class="keyword" column-name="Material Code">10001000</span>
<div id="result"></div>
That was becoz, you were using same updated array for all.
var searchCriteria = {};
var keyword = [];
$('.keyword').each(function(index, elem) {
col = $(elem).attr('column-name');
if( !searchCriteria[col])
searchCriteria[col] = [];
searchCriteria[col].push($(elem).text());
});
console.log(searchCriteria);
Here in this code im searching for, if property doesn't exist . Then make that index as array. And futher you push elements.
Working fiddle
You can instead do this
var searchCriteria = {};
$('.keyword').each(function(){
var key = $(this).attr("column-name");
var value = $('[column-name='+key+']').map(function(){return $(this).text()}).get();
if(!searchCriteria.hasOwnProperty(key)) searchCriteria[key] = value;
});

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

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;

How to create dynamically named JavaScript object properties?

Here is what I have
<form>
<input type="text" name="item1" class="grab" value="userInput" />
<input type="text" name="somethingelse1" class="grab" value="differentUserInput" />
... (any number of inputs)
</form>
Using JQuery/Javascript I want to build an array of objects with name value pairs that looks like this:
output = [ {item1: userInput}, {somethingelse1: differentUserInput} ... etc.];
I have tried this with no success:
var output = new Array();
$('.grab').each( function(index) {
output.push({$(this).attr('name'): $(this).val()} );
});
I have tried several variations including experimenting with eval(), but to no avail. If I remove the $(this).attr('name'), and give it a static name it works... so how can I create dynamically named objects?
The literal-object syntax cannot be used for non-literal keys.
To use a non-literal key with an object requires the object[keyExpression] notation, as below. (This is equivalent to object.key when keyExpression = "key", but note the former case takes an expression as the key and the latter an identifier.)
var output = []
$('.grab').each(function(index) {
var obj = {}
obj[$(this).attr('name')] = $(this).val()
output.push(obj)
})
Happy coding.
Also, consider using .map():
var output = $('.grab').map(function() {
var obj = {}
obj[$(this).attr('name')] = $(this).val()
return obj
})
I took only the id of the form as a parameter of this function:
function form2JSON(form){
var info_ser = $('#'+form).serialize();
var data = info_ser.split('&');
var output = {};
$.each( data, function( i, l ){
var data_input = l.split('=');
output[data_input[0]] = data_input[1];
});
return output;
}
The result object is something like this Object { fieldname="value", fieldname1="value1", fieldname2="value3", ...}

Categories

Resources