我有以下 JavaScript 数组:
[
{
"day": 0,
"best_hour_of_the_day": "10",
"appt_success_rate": "60",
"appt_100_numbers": "27"
},
{
"day": 2,
"best_hour_of_the_day": "10",
"appt_success_rate": "60",
"appt_100_numbers": "27"
},
{
"day": 3,
"best_hour_of_the_day": "10",
"appt_success_rate": "60",
"appt_100_numbers": "27"
},
{
"day": 4,
"best_hour_of_the_day": "10",
"appt_success_rate": "60",
"appt_100_numbers": "27"
},
{
"day": 6,
"best_hour_of_the_day": "--",
"appt_success_rate": "0",
"appt_100_numbers": "0"
}
]
我已经定义了数组,其中包含我需要的天数。
var daysOfTheWeek = [0,1,2,3,4,5,6];
我想问一下,如何将缺失项添加到 JavaScript 数组中的好方法是什么?
这意味着添加缺失值 1 和 6 以获得以下 JavaScript 结果:
[
{
"day": 0,
"best_hour_of_the_day": "10",
"appt_success_rate": "60",
"appt_100_numbers": "27"
},
{
"day": 1,
"best_hour_of_the_day": "--",
"appt_success_rate": "0",
"appt_100_numbers": "0"
},
{
"day": 2,
"best_hour_of_the_day": "10",
"appt_success_rate": "60",
"appt_100_numbers": "27"
},
{
"day": 3,
"best_hour_of_the_day": "10",
"appt_success_rate": "60",
"appt_100_numbers": "27"
},
{
"day": 4,
"best_hour_of_the_day": "10",
"appt_success_rate": "60",
"appt_100_numbers": "27"
},
{
"day": 5,
"best_hour_of_the_day": "10",
"appt_success_rate": "60",
"appt_100_numbers": "27"
},
{
"day": 6,
"best_hour_of_the_day": "--",
"appt_success_rate": "0",
"appt_100_numbers": "0"
}
]
最佳答案
我在 JAVASCRIPT 中给出了解决方案:
查看演示:
jsfiddle 链接: http://jsfiddle.net/3phba87q/
给出:
var dummyData=[
{
day: 0,
best_hour_of_the_day: "10",
appt_success_rate: "60",
appt_100_numbers: "27"
},
{
day: 2,
best_hour_of_the_day: "10",
appt_success_rate: "60",
appt_100_numbers: "27"
},
{
day: 3,
best_hour_of_the_day: "10",
appt_success_rate: "60",
appt_100_numbers: "27"
},
{
day: 4,
best_hour_of_the_day: "10",
appt_success_rate: "60",
appt_100_numbers: "27"
},
{
day: 5,
best_hour_of_the_day: "10",
appt_success_rate: "60",
appt_100_numbers: "27"
}
];
var daysOfTheWeek = [0,1,2,3,4,5,6];
为了得到预期的结果:
var existingDays = [];
// get the existing days
for(var i=0;i<dummyData.length;i++){
existingDays[i] = dummyData[i]['day'];
}
// check which day's data is missing; then create a dummy object and push it to the dummyData object
for(var i=0;i<daysOfTheWeek.length;i++){
if(existingDays.indexOf(parseInt(daysOfTheWeek[i])) < 0){
var dummyObject = {
"day": i,
"best_hour_of_the_day": "--",
"appt_success_rate": "0",
"appt_100_numbers": "0"
};
dummyData.push(dummyObject);
}
}
//sort day wise ascending
dummyData.sort(function(x,y){ return parseInt(x.day) - parseInt(y.day) });
关于javascript - 如何将缺失的项目添加到 JavaScript 数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28958249/