目前,我有一个具有
等属性的对象数组{
id: 1,
rollName: Tuna,
price: 6,
category: sushi,
quantity: 1 // whatever the quantity is that the person selects
}
每个对象都是通过用户选择动态生成的,并立即推入这些对象嵌套的数组中。
我遇到的问题是,现在我想创建一个新的对象数组,该对象基本上使用上面的数组,并使其具有诸如
{
rollName: Tuna,
quantity: 1, //whatever the quantity is that the person selects
tableNumber: 1 // preset by page
}
当前我有一个功能
function buildOrder(){
let chefObject = {};
for (let i = 0; i < tableOneOrder.length; i++) {
chefObject[i] = {
rollName : tableOneOrder[i].rollName,
quantity : tableOneOrder[i].quantity,
tableNum : tableNum
};
}
}
我的最终数组ID类似于
[{
rollName: Tuna,
quantity: 3,
tableNumber:1
},{
rollName: Freshwater Eel,
quantity: 2,
tableNumber: 1
},{
rollName: Rainbow Roll,
quantity: 1,
tableNumber: 1
}]
答案 0 :(得分:0)
您可以使用map()
遍历该数组并根据其元素构建一个新数组。您还可以使用对象分解来提取所需的字段,这使代码更易于阅读:
let arr = [
{
id: 1,
rollName: 'Tuna',
price: 6,
category: 'sushi',
quantity: 1 // whatever the quantity is that the person selects
},
{
id: 2,
rollName: 'Hamachi',
price: 7,
category: 'sushi',
quantity: 2 // whatever the quantity is that the person selects
}
]
let tableName = 1
let newObj = arr.map(({rollName, quantity}) => ({tableName, quantity, rollName}))
console.log(newObj)