我现在有一个令人困惑的问题。情况是这样的:
let example = [
{
name: "First",
id: 1,
rank: 1,
childs: [5,3] // [3,5] -> wrong, because the element which have the id: 3
//(First's second child), have the rank 2, but with id: 5 (First's first child) have the rank 1.
},
{
name: "First's first child",
id: 5,
rank: 1,
childs: [4,2]
},
{
name: "First's second child",
id: 3,
rank: 2,
childs: [6]
},
{
name: "Second's first child",
id: 4,
rank: 1,
childs: []
},
{
name: "Second's second child",
id: 2,
rank: 2,
childs: []
},
{
name: "Third's first child",
id: 6,
rank: 1,
childs: []
}
]
childs
属性是一个数组,显示元素的子ID(项的名称显示元素之间的关系)。 childs
数组的元素顺序必须与childs
具有相同ID的元素排名相等。
这里的问题是,childs
数组的排序并不总是正确的,这给我带来了很多问题。我需要做的是获取元素的子元素(数组的childs
项表示项目在example
中的id),在{{1}中搜索它们中的每一个}}数组,然后按example
中的排名顺序对childs
数组进行排序。因此,我想对example
进行排序,具体取决于example[i].childs
中相同的ID&#39项目排名。这怎么可能?
答案 0 :(得分:1)
如果我正确理解了OP,则输出是OP示例,注释是输入。 childs
属性的排序基于相应元素的排名来自“父”的childs
数组中的ID。如果这是正确的,那么您可以使用find
在数组中搜索与子ID匹配的元素,根据它们的排名对它们进行排序,然后将child
属性替换为新的排序值。
// First map over the entire example
const sorted = example.map(({childs, ...p}) => ({
// Copy all of the original element's properties except `childs`
...p,
// Replace `childs` with a sorted array
childs: childs
// Find the child element based on the ID
.map((pid) => example.find(({id: cid}) => pid === cid))
// Sort the elements based on their rank
.sort(({rank: a}, {rank: b}) => a - b)
// Pick out only the `id` value
.map(({id} = {}) => id)
}));
一个有效的例子:
const example = [{
name: "First",
id: 1,
rank: 1,
childs: [3, 2]
},
{
name: "First's first child",
id: 2,
rank: 1,
childs: [4, 5]
},
{
name: "First's second child",
id: 3,
rank: 2,
childs: [6]
},
{
name: "Second's first child",
id: 4,
rank: 1,
childs: []
},
{
name: "Second's second child",
id: 5,
rank: 2,
childs: []
},
{
name: "Third's first child",
id: 6,
rank: 1,
childs: []
}
];
const sorted = example.map(({childs, ...p}) => ({
...p,
childs: childs
.map((pid) => example.find(({id: cid}) => pid === cid))
.sort(({rank: a}, {rank: b}) => a - b)
.map(({id} = {}) => id)
}));
console.log(sorted);