QUIQUELHAPPY QUIQUELHAPPY - 1 year ago 45
Javascript Question

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.

Answer Source

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download