最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Splitting a set of strings and storing in a dynamic variable - Stack Overflow

programmeradmin2浏览0评论

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

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';
Share Improve this question edited Jun 1, 2016 at 14:25 Wes Foster 8,9005 gold badges45 silver badges64 bronze badges asked Jun 1, 2016 at 14:08 BabaBaba 2,2299 gold badges52 silver badges93 bronze badges 5
  • You can store it in an object – Akshay Commented Jun 1, 2016 at 14:09
  • Thanks Akshay. Do you have code sample? – Baba Commented Jun 1, 2016 at 14:10
  • Do you really want/need them in the global scope so you can access them by the name like Budge1 or Team1? – IMTheNachoMan Commented Jun 1, 2016 at 14:13
  • I want to be able to access them one by one and store in a database. I dont think the object will work. – Baba Commented Jun 1, 2016 at 14:18
  • "I dont think the object will work" - why it won't ? – RomanPerekhrest Commented Jun 1, 2016 at 14:19
Add a ment  | 

8 Answers 8

Reset to default 4

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

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

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

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.

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

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/hzdwfkue/1/

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

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
发布评论

评论列表(0)

  1. 暂无评论