我需要一个解决方案,将Object中的一些值( weekdayMap )添加到包含对象的现有数组( vehicleAvailabilities )中。 在第一天,我需要值 Montag 在第2天,值 Dienstag
等等
我需要这样的结果:
const result = [
{id: 1, day: "1", value: true, weekday: 'Montag'},
{id: 2, day: "2", value: true, weekday: 'Dienstag'} ...
从这两个:
const vehicleAvailabilities = [
{id: 1, day: "1", value: true},
{id: 2, day: "2", value: true},
{id: 3, day: "3", value: true},
{id: 4, day: "4", value: true},
{id: 5, day: "5", value: true},
{id: 6, day: "6", value: false},
{id: 7, day: "7", value: false}
]
const weekdayMap = {
1: 'Montag',
2: 'Dienstag',
3: 'Mittwoch',
4: 'Donnerstag',
5: 'Freitag',
6: 'Samstag',
7: 'Sonntag'
}
答案 0 :(得分:1)
这是demo,我喜欢数组地图和js
中的所有新功能代码const vehicleAvailabilities = [
{id: 1, day: "1", value: true},
{id: 2, day: "2", value: true},
{id: 3, day: "3", value: true},
{id: 4, day: "4", value: true},
{id: 5, day: "5", value: true},
{id: 6, day: "6", value: false},
{id: 7, day: "7", value: false}
]
const weekdayMap = {
1: 'Montag',
2: 'Dienstag',
3: 'Mittwoch',
4: 'Donnerstag',
5: 'Freitag',
6: 'Samstag',
7: 'Sonntag'
}
let re = vehicleAvailabilities.map(function(item){
item.weekday = weekdayMap[item.day];
return item;
})
console.log(re);
答案 1 :(得分:1)
为此制作自己的功能:
const vehicleAvailabilities = [
{id: 1, day: "1", value: true},
{id: 2, day: "2", value: true},
{id: 3, day: "3", value: true},
{id: 4, day: "4", value: true},
{id: 5, day: "5", value: true},
{id: 6, day: "6", value: false},
{id: 7, day: "7", value: false}
]
const weekdayMap = {
1: 'Montag',
2: 'Dienstag',
3: 'Mittwoch',
4: 'Donnerstag',
5: 'Freitag',
6: 'Samstag',
7: 'Sonntag'
}
function mergeMapIntoArray(map, array) {
return array.map((entry) => { entry.weekday = map[entry.id]; return entry; });
}
console.log(mergeMapIntoArray(weekdayMap, vehicleAvailabilities));

答案 2 :(得分:1)
ES6解决方案。
const a = [{id:1,day:"1",value:true},{id:2,day:"2",value:true},{id:3,day:"3",value:true},{id:4,day:"4",value:true},{id:5,day:"5",value:true},{id:6,day:"6",value:false},{id:7,day:"7",value:false}];
const b = {1:'Montag',2:'Dienstag',3:'Mittwoch',4:'Donnerstag',5:'Freitag',6:'Samstag',7:'Sonntag'};
const r = Object.keys(b).map((v, i) => ({ weekday: b[v], ...a[i] }));
console.log(r);
答案 3 :(得分:0)
这是一个使用地图的示例脚本,只需向对象添加新属性即可。
var vehicleAvailabilities = [
{id: 1, day: "1", value: true},
{id: 2, day: "2", value: true},
{id: 3, day: "3", value: true},
{id: 4, day: "4", value: true},
{id: 5, day: "5", value: true},
{id: 6, day: "6", value: false},
{id: 7, day: "7", value: false}
];
const weekdayMap = {
1: 'Montag',
2: 'Dienstag',
3: 'Mittwoch',
4: 'Donnerstag',
5: 'Freitag',
6: 'Samstag',
7: 'Sonntag'
}
var result = [];
var item;
for(var i=0;i<vehicleAvailabilities.length;i++){
item = vehicleAvailabilities[i];
item.weekday = weekdayMap[parseInt(item.day)];
result.push(item);
}
console.log(result);
&#13;
答案 4 :(得分:0)
如果你使用打字稿或ES6,你可以更容易地从@ÁlvaroTouzón提出建议:
let re = vehicleAvailabilities.map(item => item.weekday = weekdayMap[item.day])