JavaScript Split from comma separated to array list with values - javascript

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

Related

Add javascript variable in array in json format where variable value changes on mouseClick

var question="Something?";
var option="a";
var col=[];
on click the variable value changes and values should be pushed in given format. i am new to javascript please me with this. thanks
//Onclick the variable value changes
function ClickedMe(question,option)
{
col.push({"Question":question,"Option":option});
}
Output array col should be:
[{"Question":"Something","Option":"a"},{"Question":"OtherQuestion?","Option":"b"},{"Question":"otherNextQuestion?","Option":"c"}]
Try this:
function ClickedMe(question, option) {
let temp = {};
temp["Question"] = question;
temp["Option"] = question;
col.push(temp);
}
col = [{
question: 'Something',
option: 'a'
}]
function ClickMe(quest, opt){
let newObj = {}
newObj.question = question
newObj.option = opt
col.push(newObj)
}

Deleting element from a long object

I have an object that looks like this:
[{"1":{"name":"A","email":2}},
{"2":{"name":"B","email":3}},
{"3":{"name":"C","email":4}},]
{"4":{"name":"B","email":5}}]
I want to have a result like below:
[{"name":"A","email":2}},
{"name":"B","email":3}},
{"name":"C","email":4}},]
{"name":"B","email":5}}]
I tried but this code is not working, now I am a bit lost as to how to approach a solution for this.
obj.map(a => {
var newobj
a = []
a.push[a]
})
you need to read about Array.prototype.map() and the way you use it is not the proper way
var homework =[{"1":{"name":"A","email":2}},
{"2":{"name":"B","email":3}},
{"3":{"name":"C","email":4}},
{"4":{"name":"B","email":5}}];
var outputofthehomework = homework.map( s => Object.values(s)[0] );
console.log(outputofthehomework)
var a = [{"1":{"name":"A","email":2}},{"2":{"name":"B","email":3}}, {"3":{"name":"C","email":4}}, {"4":{"name":"B","email":5}}];
var b = [];
a.forEach(function(element){
for (var key in element){
b.push(element[key]);
}
});
console.log(b)

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

don't get return associative array in javascript

When i create associate array in javascript, i got a problem like that.
I want to get the value by using field name as key, but i just only got undefined.
What should i do to get value by key or which way is good approach for it.
Here is my code
function getFields(pVal){
var tmpObj = {};
str = pVal.split(",");
for(i=0;i<str.length;i++){
tmpVal = str[i].split(":");
tmpObj[tmpVal[0]] = tmpVal[1];
}
return tmpObj;
}
function JustTest(){
var fields = {};
fields = getFields("'Code':'PRJ001','Name':'Project 01'");
alert(fields['Code']);
}
Because the key is 'Code', not Code, note the single quote ', you need do alert(fields["'Code'"]);
PS: Please add ; at the end of statement, it is bad practice to omit them.
I have re-factor the code, just try this:
function getFields(pVal) {
var tmpObj = {};
var str = pVal.split(",");
for (var i = 0; i < str.length; i++) {
var tmpVal = str[i].split(":");
tmpObj[tmpVal[0]] = tmpVal[1];
}
return tmpObj;
}
function JustTest() {
var fields = { };
fields = getFields("'Code':'PRJ001','Name':'Project 01'");
alert(fields["'Code'"]);
}
if you have question please comment below about code, thanks

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