js字符串转换为具有两个值的对象

js string into an object with two values

本文关键字:两个 对象 转换 字符串 js      更新时间:2023-09-26

我正试图解决一个挑战,但它很致命。我需要把一个字符串变成一个对象。

像这样:

 { Cape Town : 9,
   George : 7,  
   Johannesburg : -1, 
   Port Elizabeth : 5
  }

但目前它还我这个:

 {
    Cape Town 9: undefined,
    George 7: undefined,
    Johannesburg -1: undefined,
    Port Elizabeth 5: undefined
 }

这是我当前的代码:

 var str = "Look at this tomorrow it will be really cold all over the country
 in Cape Town 9, in George 7, in Port Elizabeth 5 and in, Johannesburg -1"

var remove = str.replace("Look at this tomorrow it will be really cold all    over the country:", "")
.replace(" in", "").replace("in ", "").replace("in ", "").replace(" and in",     "")
var properties = remove.split(', ');
var obj = {};
properties.forEach(function(property) {
  var tup = property.split(':');
  obj[tup[0]] = tup[1];
});
console.log(obj)

这里有一个较短的解决方案:

var str = "Look at this tomorrow it will be really cold all over the country in Cape Town 9, in George 7, in Port Elizabeth 5 and in, Johannesburg -1",
  cities = str.match(/in['w, ]+?-?'d/g),
  output = {};
for (var i = 0; i < cities.length; i++) {
  var city = cities[i].replace(/in,? /, ''),   // Remove the `in` from the current city.
      split = city.split(' '),                // Split at [space]
      temp = split.pop();                    // Get the last item from the split string, which is the temperature.
  output[split.join(' ')] = parseInt(temp); // Store the temperature for the city name.
}
console.log(output);

cities导致:
["in Cape Town 9", "in George 7", "in Port Elizabeth 5", "in, Johannesburg -1"]

然后,for循环只对这些进行迭代,并从中获取城市名称和温度,然后将其存储到输出中。

在末尾的:之间有一些额外的空间

使其成为

var str = "Look at this tomorrow it will be really cold all over the country in Cape Town 9, in George 7, in Port Elizabeth 5 and in, Johannesburg -1"
var remove = str.replace("Look at this tomorrow it will be really cold all over the country", "").replace(" in", "").replace("in ", "").replace("in ", "").replace(" and in",     "")

此外,您需要按空格而不是按冒号进行第二次拆分

var obj = {};
properties.forEach(function(property) {
  var tup = property.split(/'s'd+/);
  obj[tup[0]] = property.split(" ").pop();
});

演示

var str = "Look at this tomorrow it will be really cold all over the country in Cape Town 9, in George 7, in Port Elizabeth 5 and in, Johannesburg -1"
remove = str.replace("Look at this tomorrow it will be really cold all over the country", "").replace(" in", "").replace("in ", "").replace("in ", "").replace(" and in",     "");
var properties = remove.split(', ');
var obj = {};
properties.forEach(function(property) {
  var tup = property.split(/'s'd+/);
  obj[tup[0]] = property.split(" ").pop();
});
document.body.innerHTML += JSON.stringify( obj, 0, 4 );

较短的版本可能是

var str = "Look at this tomorrow it will be really cold all over the country in Cape Town 9, in George 7, in Port Elizabeth 5 and in, Johannesburg -1";
var obj = {}; 
str.split(/'s*in's*/).forEach( function(val, index){
  if (index == 0 ) return false;
  val = val.replace(/'s*and's*/, ""); //remove if there is 'and'
  var tup = val.split(/'s/);
  var value = tup.splice(-1);
  obj[tup.join(" ")] = value.join("").replace(",", "");
});
document.body.innerHTML += JSON.stringify( obj, 0, 4 );

按空格拆分并弹出最后一个元素:

var str = "Look at this tomorrow it will be really cold all over the country '
 in Cape Town 9, in George 7, in Port Elizabeth 5 and in, Johannesburg -1"

var remove = str.replace("Look at this tomorrow it will be really cold all over the country", "")
.replace(" in", "").replace("in ", "").replace("in ", "").replace(" and in",     "")
var properties = remove.split(', ');
var obj = {};
properties.forEach(function(property) {
  var tup = property.split(' ');
  var num = tup.pop();
  obj[tup.join(' ')] = num;
});
console.log(obj);

演示小提琴

使用String.replaceString.splitString.match函数的解决方案:

var str = "Look at this tomorrow it will be really cold all over the country: in Cape Town 9, in George 7, in Port Elizabeth 5 and in, Johannesburg -1",
     items = str.replace("Look at this tomorrow it will be really cold all over the country:", "").split(','),
     geoObj = {};
items.forEach(function(v) {
    var parts = v.match(/'b([A-Z]('w|'W)+)(['d+-]+?)/g)[0].split(/'s+(?=[-+]?'d)/);
    geoObj[parts[0]] = parseInt(parts[1]);
});
console.log(geoObj);

console.log输出:

{
    "Cape Town": 9,
    "George": 7,
    "Port Elizabeth": 5,
    "Johannesburg": -1
}