我想用“ |”将字符串溢出和':',最后得到一个在数组内部具有键值关系的对象。
看起来像这样
[{key1 : red, key2 : five},{key1 : blue, key2 : six},{key1 : yellow, key2 : nine}, {key1 : black, key2 :ten}]
这就是我到目前为止
var x = "red:five|blue:six|yellow:nine|black:ten"
datesArray = [],
datesObj = {},
keys = ['key1','key2'],
dates = x.split('|');
for (var i = 0; i < dates.length; i++) {
datesArray.push(dates[i].split(':'));
}
for(var x = 0; x < datesArray.length; x++){
datesObj[keys[0]] = datesArray[x][0]
datesObj[keys[1]] = datesArray[x][1]
}
console.log(datesObj);
http://jsfiddle.net/zPS7h/4/
任何帮助表示赞赏!
最佳答案
像这样吗
http://jsfiddle.net/zPS7h/15/
var x = "red:five|blue:six|yellow:nine|black:grey";
var datesArray = [],
keys = ['key1','key2'],
dates = x.split('|');
for (var i = 0; i < dates.length; i++) {
var values = dates[i].split(':');
var dateObj = { keys[0]: values[0], keys[1]: values[1] };
datesArray.push(dateObj);
}
console.log(datesArray);
关于javascript - 将字符串转换为对象数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23596564/