【问题标题】:multiply/loop the object from an array value从数组值乘/循环对象
【发布时间】:2019-09-16 13:21:00
【问题描述】:

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

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

【问题讨论】:

  • 不清楚你的问题是什么。
  • 那么你想创建一个数组数组吗?您的最终代码块是无效语法,但如果在 = 右侧的值周围有 [] 则有效。
  • 到时候我会想办法解决的,谢谢各位!

标签: javascript arrays object ecmascript-6


【解决方案1】:

const orders = [
        {itemId: '1', quantity: 2 }, // first order
        {itemId: '2', quantity: 3 }  // second order
    ]

 // Retrieve the result of map.

    const payingItems = orders.map(function(c,i){

  // Create a temp Array to save items as quantity exists.

        const payingItem = [];
        for (var index = 0; index < c.quantity; index++)  {
            payingItem.push({
                name: 'item-'+c.itemId,
                price: 20
            })
    	}
       return payingItem
    });
    
    console.dir(payingItems);

【讨论】:

  • 很好的基本答案!如果您想在答案中添加可运行版本,here's how to do it
  • 谢谢,这是一个很好的答案,会尽快在工作中尝试:D
【解决方案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);

【讨论】:

  • 你们太棒了!谢谢,我尽快上班时试试这个
猜你喜欢
  • 2023-01-25
  • 2012-06-09
  • 2019-02-12
  • 1970-01-01
  • 2012-11-19
  • 2017-08-09
  • 2020-06-05
  • 2021-07-21
相关资源
最近更新 更多