我现在有一个令人困惑的问题。情况是这样的:
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),在 example< 中搜索它们中的每一个
数组,然后按照 example
中的排名顺序对 childs
数组进行排序。所以我想对 example[i].childs
进行排序,这取决于相同 id 项目在 example
中的排名。这怎么可能?
最佳答案
如果我正确理解了 OP,那么输出就是 OP 示例,而评论就是输入。 childs
属性的排序基于“parent”的 childs
数组中相应元素的排名。如果这是正确的,那么您可以使用 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);
关于javascript - 使用另一个数组的对象属性对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428175/