簡體   English   中英

將 javascript 中的字符串乘以 arrays,最后不加入它們

[英]Multiply arrays of strings in javascript, not joining them at the end

我正在嘗試從所選選項和選項值列表中創建產品變量列表,我擁有的數據如下所示:

[
  {
   option: "size",
   selected_values: [{id: 1, value: "XL"}, {id: 2, value: "M"}]
  },
  {
   option: "color",
   selected_values: [{id: 14, value: "Red"}, {id: 15, value: "Blue"}]
  }
]

從這些數據中我想創建這樣的東西:

[
 {
 varint_name: "XL Red",
 selected_values: [1, 14]
 },
 {
 varint_name: "XL Blue",
 selected_values: [1, 15]
 },
 {
 varint_name: "M Red",
 selected_values: [2, 14]
 },
 {
 varint_name: "M Blue",
 selected_values: [3, 15]
 }
]

考慮到所選選項和選項值的列表(第一個列表)可以是兩個以上的對象,它綁定到一個 from 所以可以或多或少使用 vue btw 的 iam,我知道我想要的列表應該是一個計算值但我想知道生成所需列表形狀的邏輯

如建議的那樣,您將需要生成所有選項值的笛卡爾積。

我添加了第三個選項來展示這適用於任何給定數量的選項。

 const options = [{ option: "size", selected_values: [ { id: 1, value: "XL" }, { id: 2, value: "M" } ] }, { option: "color", selected_values: [ { id: 14, value: "Red" }, { id: 15, value: "Blue" } ] }, { option: "length", selected_values: [ { id: 30, value: "Short" }, { id: 31, value: "Long" } ] }]; const main = () => { const product = cartesian(...options.map(o => o.selected_values)).map(values => ({ variant_name: values.map(({ value }) => value).join(' '), selected_values: values.map(({ id }) => id), })); console.log(product); }; const cartesian = (...args) => { const result = []; __cartesianHelper(result, [], 0, args); return result; } const __cartesianHelper = (result, curr, index, all) => { for (let j = 0, l = all[index].length; j < l; j++) { const copy = [...curr, all[index][j]]; if (index === all.length - 1) result.push(copy); else __cartesianHelper(result, copy, index + 1, all); } }; main();
 .as-console-wrapper { top: 0; max-height: 100%;important; }

預計 Output

[{
  variant_name: "XL Red Short",
  selected_values: [1, 14, 30]
}, {
  variant_name: "XL Red Long",
  selected_values: [1, 14, 31]
}, {
  variant_name: "XL Blue Short",
  selected_values: [1, 15, 30]
}, {
  variant_name: "XL Blue Long",
  selected_values: [1, 15, 31]
}, {
  variant_name: "M Red Short",
  selected_values: [2, 14, 30]
}, {
  variant_name: "M Red Long",
  selected_values: [2, 14, 31]
}, {
  variant_name: "M Blue Short",
  selected_values: [3, 15, 30]
},  {
  variant_name: "M Blue Long",
  selected_values: [3, 15, 31]
}]

暫無
暫無

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

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