簡體   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