Baba
Baba

Reputation: 2219

Splitting a set of strings and storing in a dynamic variable

I am getting a set of values like below from doing a split of strings

var values = [
  "Budget1-green", 
  "Team1-green", 
  "Risk1-green", 
  "Benefit1-green", 
  "Scope1-green",
  "Schedule1-green"
];

I want to be able to store the values after the - in a variable like below. Any ideas on how to do this with javascript or jQuery?

var Budget1   = 'green';
var Team1     = 'green';
var Risk1     = 'green';
var Benefit1  = 'green';
var Scope1    = 'green';
var Schedule1 = 'green';

Upvotes: 6

Views: 2846

Answers (8)

Jack jdeoel
Jack jdeoel

Reputation: 4584

You can do by split and eval.

The eval() function evaluates or executes an argument or javascript statements.

var values = [
  "Budget1-green", 
  "Team1-green", 
  "Risk1-green", 
  "Benefit1-green", 
  "Scope1-green",
  "Schedule1-green"
];
for(var i in values){
  temp = values[i].split("-");
  eval("var "+temp[0]+"='"+temp[1]+"';");
}
console.log(Budget1);//green
console.log(Scope1);//green

Upvotes: 0

Wes Foster
Wes Foster

Reputation: 8900

Using a non-object approach, in order to get exactly the solution you were looking for, would be as follows (using eval() or the window object):

var values = [
  "Budget1-green",
  "Team1-green",
  "Risk1-green",
  "Benefit1-green",
  "Scope1-green",
  "Schedule1-green"
];


// Loop through each array item
for (var i=0; i<values.length; i++)
{
   // This splits the data into separate pieces
   var split_data = values[i].split('-');

   // Here, we assign the dynamic variable using the window object
   // This is the preferred method:
   window[split_data[0]] = split_data[1];

   // Alternatively, you can use `eval` to create the variable
   // This approach is generally unsafe, so use with caution:
   eval("var " + split_data[0] + "=" + split_data[1] + ";");
}

Using the window object is the preferred method since eval can potentially be dangerous.

Also, be careful when using dynamically-created variables because it can cause confusion if, for example, there was already a variable named "Budget1" in the global scope.

Upvotes: 2

Akshay
Akshay

Reputation: 14348

Try this

This loops through each element in the array , splits it , and stores it as an object. Later you can call these values like this

objVariables["Budget1"] // returns green

var values = ["Budget1-green", "Team1-green", "Risk1-green", "Benefit1-green", "Scope1-green", "Schedule1-green"];
var objVariables = {};
for(var x=0;x<values.length;x++){
  var splitted = values[x].split("-");
  objVariables[splitted[0]] = splitted[1];
}
console.log(objVariables);

// Calling each variables 
// They all will return green since it is the data you have given 

console.log(objVariables["Budget1"]);
console.log(objVariables["Team1"]);
console.log(objVariables["Risk1"]);
console.log(objVariables["Benefit1"]);
console.log(objVariables["Scope1"]);

Upvotes: 4

IMTheNachoMan
IMTheNachoMan

Reputation: 5821

All the answers so far are to add to an object and that works but in case you need/want the global scope you could do this:

var values = ["Budget1-green", "Team1-blue", "Risk1-green", "Benefit1-green", "Scope1-green", "Schedule1-green"];

for(var i = 0, numValues = values.length; i < numValues; ++i) {
  var parts = values[i].split("-");
  window[parts[0]] = parts[1];
}

console.log(Budget1);
console.log(Team1);
console.log(Risk1);
console.log(Benefit1);
console.log(Scope1);
console.log(Schedule1);

Upvotes: 1

Stephan Muller
Stephan Muller

Reputation: 27600

Creating a new variable name on the fly is possible (using eval()) but strongly advised against. Instead, storing the data in an object would be a lot better.

By looping through the array you can do it like this:

var myVars = {};

values.forEach(function(value) {
    var split = value.split('-');
    myVars[split[0]] = split[1];
});

Now you have an object that looks like:

{ 
    Budget1: "green",
    Team1: "green",
    etc...
}

Upvotes: 0

Rajesh
Rajesh

Reputation: 24925

You can save values in object.

Array.forEach

var values = ["Budget1-green", "Team1-green", "Risk1-green", "Benefit1-green", "Scope1-green", "Schedule1-green"]

var result = {}

values.forEach(function(item){
  var o = item.split("-");
  result[o[0]] = o[1];
});

document.write("<pre>" +JSON.stringify(result,0,4)+ "</pre>")

for...of

var values = ["Budget1-green", "Team1-green", "Risk1-green", "Benefit1-green", "Scope1-green", "Schedule1-green"]

var result = {}

for(var item of values){
  var o = item.split("-");
  result[o[0]]=o[1];
}

document.write("<pre>" +JSON.stringify(result,0,4)+ "</pre>")

Upvotes: 2

Thalaivar
Thalaivar

Reputation: 23632

var values = ["Budget1-green", "Team1-green", 
       "Risk1-green", "Benefit1-green", "Scope1-green", "Schedule1-green"]

var obj = {};

values.forEach(function(val){       
    obj[val.split("-")[0]] = val.split("-")[1];        
});

Below is the fiddle: https://jsfiddle.net/hzdwfkue/1/

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

try this (store in one variable which is a map with values before - as key)

var values = ["Budget1-green", "Team1-green", "Risk1-green", "Benefit1-green", "Scope1-green", "Schedule1-green"];


var map = {}; values.forEach( function(val){ 
  var split = val.split("-"); map[ split[0] ] = split[1]; 
});

console.log(map);

Upvotes: 2

Related Questions