You should figure out which numbers are present first, for safety's sake, then turn each pair into a record. Like so:
var MyObject = {
'stop1-start': "0",
'stop1-color': "#0074a2",
'stop2-start': "32",
'stop2-color': "#ff6600"
};
function createArray(data) {
// Figure out which numbers are present
var numbers = Object.keys(data).map(function(key) {
return parseInt(key.match(/stop(\d+)/)[1], 10);
});
// Filter out duplicates
numbers = numbers.filter(function (num, idx, arr) {
// Only take the first instance of each value
return arr.indexOf(num) === idx;
}).sort();
// For each number, create a record
var records = numbers.map(function(num) {
var start = 'stop' + num + '-start';
var color = 'stop' + num + '-color';
return {
start: data[start],
color: data[color]
};
});
return records;
}
document.getElementById('r').textContent = JSON.stringify(createArray(MyObject));
<pre id=r></pre>
If you want to get all clever and functional, you can turn the whole algorithm into a single chain:
function createArray(data) {
// Figure out which numbers are present
return Object.keys(data).map(function(key) {
return parseInt(key.match(/stop(\d+)/)[1], 10);
}).filter(function (num, idx, arr) {
// Only take the first instance of each value
return arr.indexOf(num) === idx;
}).sort().map(function(num) {
var start = 'stop' + num + '-start';
var color = 'stop' + num + '-color';
return {
start: data[start],
color: data[color]
};
});
}
If you have access to ES6, you can use that for some shorthand:
function createArray(data) {
return Object.keys(data)
.map(key => parseInt(key.match(/stop(\d+)/)[1], 10))
.filter((num, idx, arr) => arr.indexOf(num) === idx)
.sort()
.map(num => {
return {
start: data[`stop${num}-start`],
color: data[`stop${num}-color`]
};
});
}