我是JS的新手,想知道将以下内容在JavaScript中转换为对象的最佳方法是什么?我想保留字符串化的键值对。
[
"\"Matt Forte : 17",
"C.J. Anderson : 16",
"Jamaal Charles : 16",
"Eddie Lacy : 15",
"Andre Ellington : 14",
"LeSean McCoy : 14",
"Marshawn Lynch : 14Tre Mason : 13",
"Latavius Murray : 13",
"Rashad Jennings : 12",
"Alfred Morris : 12",
"Jonathan Stewart : 12",
"Doug Martin : 12",
"Chris Ivory : 12",
"\""
]
我尝试了这个,但它不起作用!是否有任何内置组件可以为我做这样的事情?也许我应该将数据作为一个对象存储起来......
var players = [
"\"Matt Forte : 17",
"C.J. Anderson : 16",
"Jamaal Charles : 16",
"Eddie Lacy : 15",
"Andre Ellington : 14",
"LeSean McCoy : 14",
"Marshawn Lynch : 14Tre Mason : 13",
"Latavius Murray : 13",
"Rashad Jennings : 12",
"Alfred Morris : 12",
"Jonathan Stewart : 12",
"Doug Martin : 12",
"Chris Ivory : 12",
"\""
];
var obj = {};
for (var i = 0; i< players.length; i++) {
var tuple = players[i].split(":");
console.log(tuple);
for(var key in obj){
key = tuple[0];
obj[key] = tuple[1];
}
};
console.log(obj);
答案 0 :(得分:2)
像这样:
function prestoChango(ary){
var o = {};
for(var i=0,l=ary.length; i<l; i++){
var s = ary[i].split(/\s*\:\s*/);
o[s[0]] = +s[1];
}
return o;
}
console.log(prestoChango(arrayOfStrings));
答案 1 :(得分:2)
var stringArray = [
"\"Matt Forte : 17",
"C.J. Anderson : 16",
"Jamaal Charles : 16",
"Eddie Lacy : 15",
"Andre Ellington : 14",
"LeSean McCoy : 14",
"Marshawn Lynch : 14Tre Mason : 13",
"Latavius Murray : 13",
"Rashad Jennings : 12",
"Alfred Morris : 12",
"Jonathan Stewart : 12",
"Doug Martin : 12",
"Chris Ivory : 12",
"\""
];
var objectArray = stringArray.map(function(string) {
var splat = string.replace("\"", "").split(' : ');
var obj = {};
obj[splat[0]] = splat[1];
return obj;
});
console.log(objectArray);
答案 2 :(得分:1)
尝试使用RegExp拆分键和值:
var arr = [
"\"Matt Forte : 17",
"C.J. Anderson : 16",
"Jamaal Charles : 16",
"Eddie Lacy : 15",
"Andre Ellington : 14",
"LeSean McCoy : 14",
"Marshawn Lynch : 14Tre Mason : 13",
"Latavius Murray : 13",
"Rashad Jennings : 12",
"Alfred Morris : 12",
"Jonathan Stewart : 12",
"Doug Martin : 12",
"Chris Ivory : 12",
"\""
];
//re-build proper key-value pairs
arr = arr.join('').match(/([\w|\.\s]*\:\s\d*)/g);
var obj = {};
var l = arr.length;
var tmp;
var rgx = /\s?\:\s?/;
while (l--) {
tmp = arr[l].split(rgx);
obj[tmp[0]] = tmp[1];
}
document.write("<pre>");
document.write(JSON.stringify(arr));
document.write("<br/>");
document.write(JSON.stringify(obj, 0, 4));
document.write("</pre>");
答案 3 :(得分:1)
使用map函数创建两个新数组,分别包含键和值。
创建一个空对象,然后遍历键或值数组。
var names = players.map(function(player) { return player.split(':')[0] }
var score = players.map(function(player) { return player.split(':')[1] }
var object = {}
for (var i = 0; i < names.length; i++) {
object[names[i]] = score[i];
}
这是我的输出看起来像
{ 'Matt Forte': '17',
'C.J. Anderson': '16',
'Jamaal Charles': '16',
'Eddie Lacy': '15'
...
}
答案 4 :(得分:1)
不幸的是,使用split
的所有发布的答案都会破坏数组的最后一项。
这是一个稍微复杂的方法应该可以正常工作:
var object = {};
players.map(function(string) {
string.replace(/(.+) : (\d+)/,function($0,$1,$2){object[$1]=$2;});
});