Manipulate JSON to separate delimited attribute into separate objects

Hi,

I have a large amount of JSON being returned from a 3rd party. One of the attributes has pipe delimited list rather than in separate objects.

I would like to convert

"options": "0001|black|o0002|red|0003|gold"

to

"options": [{
	"refcode": "0001",
	"name": "black",
	"inStock": "1"
},
{
	"refcode": "0002",
	"name": "red",
	"inStock": "0"	
},
{
	"refcode": "0003",
	"name": "gold",
	"inStock": "1"	
}]

is it possible to loop through the arrays to convert this JSON on an object?

thanks

Hi cado,

Calling the split method on the pipe delimited string will give you an array of elements:

var options = data.options.split('|');

Then you can loop over the array, and use the slice method to grab a group of three elements (corresponding to an option) and assign them to an object:

var groupedOptions = [];

for (var i = 0; i < options.length; i += 3) {
	var option = options.slice(i, i+3);
	groupedOptions.push({
	    'refcode': option[0],
	    'name': option[1],
	    'inStock': option[2]
	});
}