首页 > 解决方案 > 从数组值乘/循环对象

问题描述

在一个对象数组中,我取了一个数字的数量值:

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
    ],

标签: javascriptarraysobjectecmascript-6

解决方案


听起来您想将对象数组转换为数组数组,子数组包含由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);


推荐阅读