How to create dynamically named JavaScript object properties? - javascript

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", ...}

Related

JavaScript Split from comma separated to array list with values

What I'm trying to do is from a comma separated text (like this one):
hello,test,ciao
Get a javascript array with a predetermined value.
I know how to split a comma-separated list, but I don't know how to add a value inside them.
Actual code:
HTML
<input onkeyup="test()" type="text" id="origin">
<div id="response">
</div>
JAVASCRIPT:
function getValue(){
var returnV = $("#origin").val();
return returnV
}
function test(){
var origin = getValue();
var array = origin.split(',');
console.log(array)
}
OUTPUT
["hello", "test", "ciao"]
WHAT I'M TRYING TO GET
{
"hello":"predetermined value",
"test":"predetermined value",
"ciao":"predetermined value",
}
I think this question is interesting because this way yo can, for example, create new configurations with a starter value and add custom confirgurations for each of them later. I know that the split part is already replied on stackoverflow, what I'm having trouble with is with adding the default values :), thank you very much in advance.
didn't want to change your code so much. just have a look up to object creation.
function getValue(){
return document.getElementById("origin").value
}
function test(){
var obj = {}
var origin = getValue();
origin.split(", ").forEach(function(e) {
obj[e] = "predeterminated value";}
);
console.log(obj);
}
<input onkeyup="test()" type="text" id="origin">
<div id="response">
</div>
Have you tried iterating over the array? Like this:
function getValue(){
var returnV = $("#origin").val();
return returnV
}
function test(){
var origin = getValue();
var object = {}
var array = origin.split(',');
array.forEach((item) => {
object[item] = "predeterminated value"
}
console.log(object)
}
A couple notes: try to give more meaningful names to your variables; the word is "predetermined",
Store your output to a variable:
var output=["hello", "test", "ciao"]
Then do something like this with it:
var newObject={};
for(var i in output){
var property=output[i];
newObject[property]='predeterminated value';
}
Example JSFiddle (open console to see result)
Split your string and then use Array.prototype.reduce to build an object from it.
var original = "hello,test,ciao";
var obj = original.split(',').reduce(function(p,c) {
p[c] = "predeterminated value";
return p;
}, {});
console.log(obj);
It's not exactly clear where predeterminated value is supposed to come from. If it's the same for all properties of your object, then this will work as-is. If it's not, you'll have to figure out how to select the right value.
Hey you can follow the below code snippet this will help
function getValue(){
var returnV = 'hey,your,input,keys,goes,here';
return returnV;
}
function test(){
var origin = getValue();
var array = origin.split(',');
var finalObj = {};
var defaultVal = 'pre-def';
for(var i=0;i<array.length;i++){
finalObj[array[i]] = defaultVal;
}
console.log("arry",array)
console.log("converted",finalObj)
}
test();

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.

create array, use $.each to loop, and add value if not in array

I have a bunch of .defined in a text and want to create an array of unique values with javascript. So basically, for each anchor with class defined, I want to first check the array to see if the pair already exists. If exists, go to next anchor. If does not exist, add to array. This is the code I have tried using, but it does not remove duplicate values.
var arr = new Array();
y = 0;
$("a.defined").each(function() {
var spanishWord = this.text;
var englishWord = this.title;
if(spanishWord in arr) {
console.log("do nothing");
} else {
arr.push({key: spanishWord, value: englishWord});
y++;
}
For example, I have these tags in the text:
<a title="read">Leer</a>
<a title="work">Trabajar</a>
<a title="like">Gustar</a>
<a title="read">Leer</a>
<a title="sing">Cantar</a>
<a title="like">Gustar</a>
And I would like my array to look like:
Spanish Word | English Word
Leer read
Trabajar work
Gustar like
Cantar sing
but instead it looks like:
Spanish Word | English Word
Leer read
Trabajar work
Gustar like
Leer read
Cantar sing
Gustar like
Any ideas?
I would do this in two steps.. one to eliminate duplicates, and one to create the array:
http://jsfiddle.net/uN4js/
var obj = {};
$('a.defined').each(function() {
obj[this.text] = this.title;
});
var arr = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop))
arr.push({key: prop, value: obj[prop]});
};
console.log(arr);
If the object is sufficient and you don't really need an array, you could stop after the object is created.
You can probably just use a javascript object here:
var dict = {};
y = 0;
$("a.defined").each(function() {
var spanishWord = this.text;
var englishWord = this.title;
dict[spanishWord] = englishWord;
}
And there isn't really a need for unique checks, since newer values will just overwrite the older ones. If you don't want that behaviour, you can do this:
var dict = {};
y = 0;
$("a.defined").each(function() {
var spanishWord = this.text;
var englishWord = this.title;
if (!(spanishWOrd in dict)) {
dict[spanishWord] = englishWord;
}
}
Javascript's in operator is not used for testing inclusion, it's used for iteration in a for .. in .. loop.
Other answers have suggested correctly that you need either .indexOf or JQuery's $.inArray method to test inclusion in an array, but there is a simpler (and faster) way of solving this problem: use a dictionary of key/value pairs instead!
var dict = {};
$("a.defined").each(function() {
dict[this.textContent] = this.title;
});
Afterwards, you can use for key in dict to iterate over the list of unique Spanish words, and dict[key] to get the corresponding English translation.
Try this:
JavaScript
var arr = {};
$("a").each(function() {
var spanishWord = this.text;
var englishWord = this.title;
if(spanishWord in arr) {
console.log("do nothing");
} else {
arr[spanishWord] = englishWord;
}
});
console.log(arr);

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

Creating a JSON dynamically with each input value using jquery

I got a situation where I would like to read some data off a JSON format through PHP, however I am having some issues understanding how I should construct the Javascript object to create the JSON format dynamically.
My scenario is as follows:
<input title="QA" type="text" class="email">
<input title="PROD" type="text" class="email">
<input title="DEV" type="text" class="email">
The Javascript code I have so far goes through each input grabs the data, I am however unable to understand how to process from here on.
var taskArray = {};
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
//how to create JSON?
});
I would like to get the following output if possible.
[{title: QA, email: 'a#a.com'}, {title: PROD, email: 'b#b.com'},{title: DEV, email: 'c#c.com'}]
Where the email is acquired by the input field value.
Like this:
function createJSON() {
jsonObj = [];
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
item = {}
item ["title"] = id;
item ["email"] = email;
jsonObj.push(item);
});
console.log(jsonObj);
}
Explanation
You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.
If you need a string, then do
jsonString = JSON.stringify(jsonObj);
Sample Output
[{"title":"QA","email":"a#b"},{"title":"PROD","email":"b#c"},{"title":"DEV","email":"c#d"}]
I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.
Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.
See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.
In your case:
var array = [];
$("input[class=email]").each(function() {
array.push({
title: $(this).attr("title"),
email: $(this).val()
});
});
// then to get the JSON string
var jsonString = JSON.stringify(array);
May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.
var obj = [];
var elems = $("input[class=email]");
for (i = 0; i < elems.length; i += 1) {
var id = this.getAttribute('title');
var email = this.value;
tmp = {
'title': id,
'email': email
};
obj.push(tmp);
}
same from above example - if you are just looking for json (not an array of object) just use
function getJsonDetails() {
item = {}
item ["token1"] = token1val;
item ["token2"] = token1val;
return item;
}
console.log(JSON.stringify(getJsonDetails()))
this output ll print as (a valid json)
{
"token1":"samplevalue1",
"token2":"samplevalue2"
}
I tried this:
// Sample JS object
var varobject = {
name: "Name",
Intern: "Test",
};
// Converting JS object to JSON string
JSON.stringify(varobject);

Categories

Resources