我有一个带有一些键的基本对象,以及具有相似但不一定完全相同的键的对象列表。
const o1 = {k1: "", k2: "", k3: ""} // the basic object
const o2 = {k1: "", k4: ""} // 1 the same key
const o3 = {k1: "", k3: ""} // 2 the same keys
const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
const o5 = {k5: ""} // 0 the same keys
我想编写一个函数,它接受基础对象和其他对象的数组,并根据给定对象中相似键的数量对它们进行排序。
function order(obj, arr) {
// ...
}
结果应该是给定对象的有序数组,该数组基于与基对象相同的键的数量。
order(o1, [o2, o3, o4, o5])
// result: [o4, o3, o2, o5]
你会用它做什么?
我在考虑按对象键的交集长度排序。
最佳答案
您可以计算相同的键并使用此值进行排序。
const
o1 = { k1: "", k2: "", k3: "" }, // the basic object
o2 = { k1: "", k4: "" }, // 1 the same key
o3 = { k1: "", k3: "" }, // 2 the same keys
o4 = { k3: "", k1: "", k2: "" }, // 3 the same keys
o5 = { k5: "" }; // 0 the same keys
function order(object, array) {
function getCount(o) {
return Object.keys(object).reduce((s, k) => s + (k in o), 0);
}
return array.sort((a, b) => getCount(b) - getCount(a));
}
console.log(order(o1, [o2, o3, o4, o5])); // [o4, o3, o2, o5]
关于javascript - 如何按与作为参数的给定键相同的键数对对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53378929/