我需要遍历相同的对象并根据用户所食用的n餐数进行打印。我有以下数组
[id, name, food1, food2, food3],
[id, name, food1, food2, ''],
[id, name, food1, '', '']
在数据库中应该是这样的:
1 | Ronald| chicken rice | NoFood1
2 | Ronald| Tortillas azadas | NoFood2
3 | Ronald| stewed chicken | NoFood3
4 | Paul | Arepas | NoFood1
5 | Paul | Torillas | NoFood2
6 | Raul | noodles | NoFood1
因为记录是基于每个用户的食物量,但是通过使用代码,我为我带来了每个对象的第一个食物,所以我看到有些示例包含链表和.push,但是如果有的话我可以使用另一个代码,但是如果您可以或多或少地向我展示使用我的代码,或者如果有另一个实现,请多多指教。
My function
ConditionDataToSend(lines, values: Array<any>){
while (lines !== null) {
const info: FoodDto = {food: '', name: '', id:0, noFood:''}
if (values.length >= 4 && values[4] !== '') {
info.name = values[1]
info.food = values[2]
info.noFood = 'food1'
info.id = id
return info
}
if (values.length >= 5 && values[5] !== '') {
info.name = values[1]
info.food = values[2]
info.nofood = 'food2'
info.id = id
return info
}
....
答案 0 :(得分:0)
我对这个问题(特别是noFood
属性)感到有些困惑,但这能满足您的要求吗?
const data = [
[1, 'Jim', 'raspberry', 'blackberry', 'lingonberry'],
[2, 'Tina', 'boysenberry', 'strawberry', ''],
[3, 'Sarah', 'blueberry', '', '']
];
function infoTransform(values) {
return values.map(value => {
[id, name, ...foods] = value;
return {
id,
name,
foods: foods.filter(food => food !== '')
};
});
}
console.log(infoTransform(data));
/* Log:
[
{
id: 1,
name: 'Jim',
foods: [ 'raspberry', 'blackberry', 'lingonberry' ]
},
{ id: 2, name: 'Tina', foods: [ 'boysenberry', 'strawberry' ] },
{ id: 3, name: 'Sarah', foods: [ 'blueberry' ] }
]
*/
编辑:使用noFood
更新了代码:
const data = [
[1, 'Jim', 'raspberry', 'blackberry', 'lingonberry'],
[2, 'Tina', 'boysenberry', 'strawberry', ''],
[3, 'Sarah', 'blueberry', '', '']
];
function infoTransform(values) {
return values.map(value => {
// Destructure
let [id, name, ...foods] = value;
// Filter out empty strings
foods = foods.filter(food => food !== '');
// Set food and noFood properties
let noFood = null;
let food = null;
if (foods.length === 1) {
noFood = foods[0];
food = foods[0];
} else if (foods.length > 1) {
noFood = foods[foods.length - 1];
food = foods[0];
}
return {
id,
name,
food,
noFood
};
});
}
console.log(infoTransform(data));
/* Log:
[
{ id: 1, name: 'Jim', food: 'raspberry', noFood: 'lingonberry' },
{ id: 2, name: 'Tina', food: 'boysenberry', noFood: 'strawberry' },
{ id: 3, name: 'Sarah', food: 'blueberry', noFood: 'blueberry' }
]
*/