我有两个对象说firstObject
和secondObject
。现在我必须对firstObject
进行排序,使其值与secondObject
匹配。这是对象
firstObject
0:{id: 23, code: "SONGS", value: "Songs"}
1:{id: 24, code: "ATHELETE", value: "Athelete"}
2:{id: 25, code: "DANCE", value: "Dance"}
3:{id: 28, code: "MUSIC_BASE", value: "Music base"}
4:{id: 31, code: "SPORTS", value: "Sports"}
secondObjects
{"Sports":2,"Dance":3,"Music base":4,"Athelete":3,"Songs":1}
排序后firstObject
应该有订单Sports ,Dance ,Music base ,Athelete ,Songs
答案 0 :(得分:0)
你需要有一个比较Object.keys(secondObj).indexOf(a.value) - Object.keys(secondObj).indexOf(b.value)
的功能。因为你需要根据当前元素的值来比较secondObj中键的值索引。
var firstObj = [{id: 23, code: "SONGS", value: "Songs"},
{id: 24, code: "ATHELETE", value: "Athelete"},
{id: 25, code: "DANCE", value: "Dance"},
{id: 28, code: "MUSIC_BASE", value: "Music base"},
{id: 31, code: "SPORTS", value: "Sports"}]
var secondObj = {"Sports":2,"Dance":3,"Music base":4,"Athelete":3,"Songs":1};
var sorted = firstObj.sort(
(a,b) => Object.keys(secondObj).indexOf(a.value) - Object.keys(secondObj).indexOf(b.value)
);
console.log(sorted);
答案 1 :(得分:0)
正如我在对原始问题的评论中所说的那样,对象密钥不能保证订购,所以你的问题本质上是有缺陷的。
但是如果我们想要假设你总是在对象键保持有序的引擎中运行,你可以这样做:
let firstObj = [{id: 23, code: "SONGS", value: "Songs"},
{id: 24, code: "ATHELETE", value: "Athelete"},
{id: 25, code: "DANCE", value: "Dance"},
{id: 28, code: "MUSIC_BASE", value: "Music base"},
{id: 31, code: "SPORTS", value: "Sports"}];
let secondObj = {"Sports":2,"Dance":3,"Music base":4,"Athelete":3,"Songs":1};
let newArray = [];
Object.keys(secondObj).forEach(key => {
newArray.push(firstObj.find(o => o.value === key));
});
newArray
将firstObj与secondObj中的键具有相同的顺序