Reputation: 188
I would like to spilt the string by '|' and ':' and end up with an object with a key value relationship inside of an array.
It would look like this
[{key1 : red, key2 : five},{key1 : blue, key2 : six},{key1 : yellow, key2 : nine}, {key1 : black, key2 :ten}]
This is what I have so far
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);
Any help is appreciated !
Upvotes: 1
Views: 89
Reputation: 23502
In ECMA5 you could do something like this using 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));
Output
[{"key1":"red","key2":"five"},{"key1":"blue","key2":"six"},{"key1":"yellow","key2":"nine"},{"key1":"black","key2":"ten"}]
On jsFiddle
Upvotes: 0
Reputation: 5492
Something like this?
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);
Upvotes: 2
Reputation: 417
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);
Upvotes: 0
Reputation: 485
Something like this would work:
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);
Upvotes: 0