javascript - 从数组值乘/循环对象
问题描述
在一个对象数组中,我取了一个数字的数量值:
orders = [
{itemId: '1', quantity: 2 }, // first order
{itemId: '2', quantity: 3 } // second order
]
然后将对象推入并从数量值乘以
乘以:
let payingItem = orders.map({
name: `item-${order.itemId}`,
price: 20
})
要拥有这个:
// first order
payingItem =
[
{ name: item-1, price: 20}, // 1
{ name: item-1, price: 20} // 2
],
// second order
payingItem =
[
{ name: item-2, price: 20}, // 1
{ name: item-2, price: 20} // 2
{ name: item-2, price: 20} // 2
],
解决方案
听起来您想将对象数组转换为数组数组,子数组包含由quantity
.
如果是这样,那么您就在正确的轨道上map
,但是您需要向它传递一个函数,并且该函数必须返回对象数组,如下所示:
const orders = [
{itemId: '1', quantity: 2 }, // first order
{itemId: '2', quantity: 3 } // second order
];
// Map the orders to an array of arrays
const payingItems = orders.map(({itemId, quantity}) =>
// Create this array by filling it in with as many
// objects as `quantity` says it should have
Array.from(Array(quantity), () => ({
name: `item-${itemId}`, price: 20
}))
);
console.log(payingItems);
这使用map
传入一个函数,该函数通过使用Array(quantity)
然后Array.from
的映射功能创建并返回子数组,以从包含对象的数组创建一个新数组。
该版本使用简洁的箭头函数,可能会稍微模糊含义,所以这里是详细的箭头函数版本,它稍微更明确地做同样的事情:
const orders = [
{itemId: '1', quantity: 2 }, // first order
{itemId: '2', quantity: 3 } // second order
];
// Map the orders to an array of arrays
const payingItems = orders.map(({itemId, quantity}) => {
// Create this array by filling it in with as many
// objects as `quantity` says it should have
const subarray = Array.from(Array(quantity), () => {
const obj = {name: `item-${itemId}`, price: 20};
return obj;
});
return subarray;
});
console.log(payingItems);
推荐阅读
- ebpf - 使用 attach_xdp,标志是否控制模式?
- asp.net - 在 docker 容器中安装 ASP.Net 3.5
- reactjs - 如何从导入文件名中删除路径以响应 NPM 构建
- javascript - 如何在垂直滑块同步光滑滑块中保持主幻灯片和垂直幻灯片的高度相同?
- sql-server - 将电源查询迁移到 SSAS 或 SSIS?
- node.js - 更新网络服务器时如何更新主屏幕应用程序
- python - 在python中选择句子
- forms - Asp .Net Core Razor Forms:验证失败后重新填充新集合项
- python - 日期范围之间的Python熊猫数据透视表
- java - 为什么 siAssignableFor 为类实现接口返回 false