我想通过'|'将字符串溢出和':'并最终得到一个在数组内部具有键值关系的对象。
看起来像这样
[{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);
任何帮助表示赞赏!
答案 0 :(得分:1)
这样的东西?
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);
答案 1 :(得分:0)
这样的事情会起作用:
s = "red:five|blue:six|yellow:nine|black:ten";
groups = s.split("|");
result = {};
for (i = 0; i < groups.length; i++) {
t = groups[i].split(":");
result[i] = { "key1": t[0], "key2": t[1] };
}
console.log(result);
答案 2 :(得分:0)
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(':'));
}
var arr = [];
for(var x = 0; x < datesArray.length; x++){
datesObj[keys[0]] = datesArray[x][0]
datesObj[keys[1]] = datesArray[x][1]
arr.push(datesObj);
}
console.log(arr);
答案 3 :(得分:0)
在ECMA5中,您可以使用Array.prototype.map
执行此类操作。
的Javascript
var x = 'red:five|blue:six|yellow:nine|black:ten',
y = x.split('|').map(function (group) {
var vals = group.split(':');
return {
key1: vals.shift(),
key2: vals.shift()
};
});
console.log(JSON.stringify(y));
输出
[{"key1":"red","key2":"five"},{"key1":"blue","key2":"six"},{"key1":"yellow","key2":"nine"},{"key1":"black","key2":"ten"}]
上