繁体   English   中英

如何有效地将 object 拆分为数组中的多个对象

[英]how to split an object to multiple objects inside an array efficiently

我有一个示例数组bunch作为

let bunch = [{fruit: "apple" , quantity: 1},{fruit: "banana" , quantity: 3}]

我正在尝试将 object 拆分为其数量时间 --> 如果fruitbananaquantity > 1为:

//newBunch --> [{fruit: "apple" , quantity: 1},{fruit: "banana" , quantity: 1},{fruit: "banana" , quantity: 1},{fruit: "banana" , quantity: 1}]

我尝试使用 reduce 作为:

 let bunch = [{fruit: "apple", quantity: 1},{fruit: "banana", quantity: 3}] let res = bunch.reduce((acc,curr)=>{ if(curr.quantity > 1 && curr.fruit==='banana'){ var arr = [] for(let i=0; i < curr.quantity; i++){ var fr = {} fr.fruit = 'banana'; fr.quantity = 1; arr.push(fr) } acc.push(...arr) } else{ acc.push(curr) } return acc },[]) console.log(res)

我使用上面的代码片段得到了预期的 o/p,但是会有一种有效的方法来做到这一点(可能代码更少),或者你会建议 go 使用当前的解决方案吗? 请指导我。 TIA

您可以使用.forEach()方法遍历数组,然后根据quantity属性的值创建新对象。 您可以将这些新创建的对象推送到另一个包含所有对象的数组中。

 let bunch = [ { fruit: 'apple', quantity: 1 }, { fruit: 'banana', quantity: 3 }, ]; const result = []; bunch.forEach(obj => { for (let i = 1; i <= obj.quantity; i++) { result.push({...obj, quantity: 1 }); } }); console.log(result);

您可以使用flatMapArray.prototype.fill

let bunch = [{fruit: "apple" , quantity: 1},{fruit: "banana" , quantity: 3}]
let result = bunch.flatMap((fruit) => {
  return Array(fruit.quantity).fill({ ...fruit, quantity: 1})
})

您可以使用Array.prototype.reduce()来遍历您的源数组。

 const src = [{fruit: "apple", quantity: 1},{fruit: "banana", quantity: 3}], result = src.reduce((acc, {fruit, quantity}) => { acc.push(...Array(quantity).fill().map(_ => ({ fruit, quantity: 1 })) ) return acc }, []) console.log(result)
 .as-console-wrapper{min-height:100%;}

我建议使用Array.prototype.flatMap()Array.from()

 let bunch = [ { fruit: 'apple', quantity: 2 }, { fruit: 'banana', quantity: 3 }, { fruit: 'starfruit', quantity: 1 }, ]; const splitBunches = bunch.flatMap((fruit) => ( Array.from({ length: fruit.quantity }, () => ({...fruit, quantity: 1 })) )) console.log(splitBunches)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM