簡體   English   中英

合並多個arrays,轉換成Angular中的另一個object數組

[英]Combine multiple arrays and convert it to another object array in Angular

我看到很多類似的問題。 但他們都沒有幫助我滿足我的需要。 所以我發布了這個問題。

根據用戶的選擇,我有多個 arrays。 作為示例,我將在這里使用 2 arrays。

color = [{id: 1, name: "Red"}, {id: 2, name: "Green"}, {id: 1, name: "Blue"}]
size = [{id: 1, name: "Small"}, {id: 2, name: "Medium"}]

我想獲得給定 arrays 的所有可能組合,並在其上添加一些鍵作為 output。

我預期的 output 如下所示。

[{"color": "Red", "size": "Small", "price":0, "Quantity": 0},
{"color": "Red", "size": "Medium", "price":0, "Quantity": 0},
{"color": "Green", "size": "Small", "price":0, "Quantity": 0},
{"color": "Green", "size": "Medium", "price":0, "Quantity": 0},
{"color": "Blue", "size": "Small", "price":0, "Quantity": 0},
{"color": "Blue", "size": "Medium", "price":0, "Quantity": 0}]

如果用戶給出 3 arrays 那么它應該相應地創建組合,但是屬性"price""Quantity"將被添加到組合中。

請向我建議如何在 Angular 中實現這一目標?

通過列表只需 go 並構建對象:

 const colors = [{id: 1, name: "Red"}, {id: 2, name: "Green"}, {id: 1, name: "Blue"}] const sizes = [{id: 1, name: "Small"}, {id: 2, name: "Medium"}] const otherProps = {price:0, Quantity: 0} const res = colors.flatMap(color => sizes.map(size => ({color: color.name, size: size.name, ...otherProps}))) console.log(res)

如果你有任意數量的 arrays,你需要找到一種方法來為它指定鍵,例如將它們放入 object:

 const data = { color: [{id: 1, name: "Red"}, {id: 2, name: "Green"}, {id: 1, name: "Blue"}], sizes: [{id: 1, name: "Small"}, {id: 2, name: "Medium"}], stuff: [{name: 'foo'}, {name: 'bar'}] } const otherProps = {price:0, Quantity: 0} const result = Object.entries(data).map( ([propName, values]) => values.map(v =>({[propName]: v.name}))) // build the key-value pairs, ie [{color: 'Red'}, ...].reduce( (groups, props) => groups.length === 0? props: groups.flatMap(group => props.map(prop => ({...group, ...prop, ...otherProps}))) // add new properties to existing groups ); console.log(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM