gpt4 book ai didi

javascript - 通过另一个对象数组引用对对象数组进行排序

转载 作者:行者123 更新时间:2023-12-03 21:07:24 25 4
gpt4 key购买 nike

我需要一些帮助来整理这些数据,我有一系列产品,我需要通过设置配置进行排序和显示。如果显示为真,则输出必须与设置数组(索引)具有相同的顺序。提前致谢。这是我尝试过的:

var products = [
{id: 0, name: 'Chocolate', category: 'Sweet'},
{id: 1, name: 'Almendras', category: 'Fruit'},
{id: 2, name: 'Nueces', category: 'Fruit'},
{id: 3, name: 'Mermelada', category: 'Jam'},
{id: 4, name: 'Alfajor', category: 'Sweet'},
{id: 5, name: 'Queso', category: 'UwU'},
{id: 6, name: 'Arandanos', category: 'Fruit'},
{id: 7, name: 'Maracuya', category: 'Fruit'}
];

let settings = [
{
name: 'Fruit',
display: true
},
{
name: 'Jam',
display: false
},
{
name: 'Sweet',
display: true
},
{
name: 'UwU',
display: true
}
]


let group = products.reduce((r, a) => {
r[a.category] = [...r[a.category] || [], a];
return r;
}, {});

let arrangedProducts = Object.keys(group);

console.log(group);
console.log(arrangedProducts);

这是我的预期输出:

/*
expected result = [
[
{id: 1, name: 'Almendras', category: 'Fruit'},
{id: 2, name: 'Nueces', category: 'Fruit'},
{id: 6, name: 'Arandanos', category: 'Fruit'},
{id: 7, name: 'Maracuya', category: 'Fruit'}
],
[
{id: 0, name: 'Chocolate', category: 'Sweet'},
{id: 4, name: 'Alfajor', category: 'Sweet'}
],
[
{id: 5, name: 'Queso', category: 'UwU'}
]
]
*/

最佳答案

解决方案

  1. 组建团队
  2. 应用设置并检索结果

const products = [
{ id: 0, name: "Chocolate", category: "Sweet" },
{ id: 1, name: "Almendras", category: "Fruit" },
{ id: 2, name: "Nueces", category: "Fruit" },
{ id: 3, name: "Mermelada", category: "Jam" },
{ id: 4, name: "Alfajor", category: "Sweet" },
{ id: 5, name: "Queso", category: "UwU" },
{ id: 6, name: "Arandanos", category: "Fruit" },
{ id: 7, name: "Maracuya", category: "Fruit" },
];

const productsGroup = products.reduce((r, a) => {
r[a.category] = [...(r[a.category] || []), a];
return r;
}, {});

function applySettings(settings) {
return settings.filter((s) => s.display).map((s) => productsGroup[s.name]);
}

console.log(
applySettings([
{
name: "Fruit",
display: true,
},
{
name: "Jam",
display: false,
},
])
);

console.log(
applySettings([
{
name: "Fruit",
display: true,
},
{
name: "Sweet",
display: true,
},
{
name: "UwU",
display: true,
},
])
);

关于javascript - 通过另一个对象数组引用对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65676914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com