这是我的一个对象。
var MyObject = {
'stop1-start': "0",
'stop1-color': "#0074a2",
'stop2-start': "32",
'stop2-color': "#ff6600"
};
这是我需要的数组。
var newArray =[
{
'stop-start': "0",
'stop-color': "#0074a2",
},
{
'stop-start': "32",
'stop-color': "#ff6600",
}
];
我尝试了循环,jquery每个但只是无法绕过它。
感谢任何帮助。
答案 0 :(得分:3)
出于安全考虑,您应该首先确定哪些数字存在,然后将每对数字转换为记录。像这样:
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>
&#13;
如果您希望获得所有智能和功能,可以将整个算法转换为单个链:
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]
};
});
}
如果您有权访问ES6,可以使用它来获取一些简写:
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`]
};
});
}
答案 1 :(得分:1)
不保证对象键有序,因此您需要在键本身内找到数组的索引:
var MyObject = {
'stop1-start': "0",
'stop1-color': "#0074a2",
'stop2-start': "32",
'stop2-color': "#ff6600"
};
var newArray= [];
Object.keys(MyObject).sort().forEach(function(key) {
var num= key.match(/(\d+)/)[0] - 1;
newArray[num] = newArray[num] || {};
newArray[num][key.replace(num+1,'')]= MyObject[key];
});
document.body.innerHTML= JSON.stringify(newArray);
&#13;
答案 2 :(得分:1)
尝试:
var newArray = [], current = {}, i = 0;
for(var key in MyObject){
current[i % 2 ? "stop-color" : "stop-start"] = MyObject[key];
i++ % 2 && (newArray.push(current), current = {})
}
<强> Demo 强>