1

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);

http://jsfiddle.net/zPS7h/4/

Any help is appreciated !

4 Answers 4

2

Something like this?

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.