这是我拥有的一个对象。
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",
}
];
我尝试了 for 循环、jquery,但就是无法理解它。
感谢任何帮助。
最佳答案
为了安全起见,你应该首先找出存在哪些数字,然后将每对数字都变成一条记录。就像这样:
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>
如果你想变得聪明和实用,你可以将整个算法变成一个单一的链:
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`]
};
});
}
关于javascript - 需要帮助根据给定的对象值构建 JavaScript 数组。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30647500/