从现有数组创建一个新数组,将每个值连接到一个唯一的值中,并检查新数组中是否已设置了唯一的连接值



我正在尝试创建一个表单来上传带有变体的产品。

我将originalArray中的每个值连接到newArray中的一个唯一值中。将值合并为一个唯一值的示例:红色/小型/现代

但是,我想检查newArray中是否已经有一个唯一的(联接的(值。如果为true,请在newArray中保留现有的值和价格。

因此,如果值";红色/小/现代";已经存在,价格为888,价格为null的数组项不应返回到newArray中。

let originalArray = [
[
{ value: 'red', id: 99, price: null },
{ value: 'blue', id: 100, price: null },
],
[
{ value: 'small', id: 101, price: null },
{ value: 'medium', id: 102, price: null },
],
[
{ value: 'modern', id: 103, price: null },
{ value: 'classic', id: 104, price: null },
],
];
//
// existing array item
let newArray = [
{ value: 'red/small/modern', id: 1, price: 888 },
{ value: 'blue/medium/modern', id: 2, price: 100 },
];
//
console.log('example 1:', newArray); // [{…}, {…}]
//
newArray = originalArray
.map((elem) => {
return elem.map(({ value }) => value);
})
.reduce((acc, cur) => {
return acc.flatMap((seq) => {
return cur.map((part) => `${seq}/${part}`);
});
})
.map((elem) => {
return { value: elem, price: null };
});
//
//
// price for value "red/small/modern" and "blue/medium/modern" should not be null, as they are already set in the newArray
console.log('example 2:', newArray);

希望这个问题有意义。

您可以将filter中尚未存在的元素放入newArray中,并将新元素推入其中:

let originalArray=[[{value:"red",id:99,price:null},{value:"blue",id:100,price:null}],[{value:"small",id:101,price:null},{value:"medium",id:102,price:null}],[{value:"modern",id:103,price:null},{value:"classic",id:104,price:null}]];
let newArray=[{value:"red/small/modern",id:1,price:888},{value:"blue/medium/modern",id:2,price:100}];
const allCombinations = originalArray
.map((elem) => {
return elem.map(({ value }) => value);
})
.reduce((acc, cur) => {
return acc.flatMap((seq) => {
return cur.map((part) => `${seq}/${part}`);
});
})
.map((elem) => ({ value: elem, price: null }));
newArray.push(
...allCombinations.filter(({ value }) => {
return newArray.every(existing => existing.value !== value);
})
);
console.log('example 2:', newArray);
.as-console-wrapper { max-height: 100%!important; }

最新更新