我有一个如下的对象数组。
var options = [
{value: 'b', label: "test1"},
{value: 'a', label: "test12"},
{value: 'c', label: "test123"}
]
以及如下的排名数组。
var ranks = [
{rank: 1, value: "a"},
{rank: 2, value: "b"},
{rank: 3, value: "c"}
]
现在我需要根据options
数组中的rank
属性对ranks
数组进行排序
答案 0 :(得分:1)
尝试一下:
var options = [
{value: 'b', label: "test1"},
{value: 'a', label: "test12"},
{value: 'c', label: "test123"}
]
var ranks = [
{rank: 1, value: "a"},
{rank: 2, value: "b"},
{rank: 3, value: "c"}
]
options.sort((a, b) => {
return ranks.find(_ => _.value === a.value).rank - ranks.find(_ => _.value === b.value).rank
})
console.log (options)
答案 1 :(得分:1)
使用ES6,您可以使用Map
并将其作为排序的闭包。
var options = [{ value: 'b', label: "test1" }, { value: 'a', label: "test12" }, { value: 'c', label: "test123" }],
ranks = [{ rank: 1, value: "a" }, { rank: 2, value: "b" }, { rank: 3, value: "c" }];
options.sort(
(m => ({ value: a }, { value: b }) => m.get(a) - m.get(b))
(ranks.reduce((m, { rank, value }) => m.set(value, rank), new Map))
);
console.log(options);
答案 2 :(得分:0)