我正在尝试解决一个挑战,但它是致命的。我需要将字符串更改为对象。
像这样:
{ 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);
城市
结果:
[“在开普敦 9”、“在乔治 7”、“在伊丽莎白港 5”、“在约翰内斯堡 -1”]
然后 for
循环只是迭代这些并从中获取城市名称和温度,然后将其存储到输出。
关于javascript - js 字符串转换为具有两个值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37179975/