作者:rita | 来源:互联网 | 2023-06-02 14:15
I have an array of objects like so:
我有一个像这样的对象数组:
var data = {
a: [
{ keyone:'c', keytwo: 'anna', keythree: 21, keyfour: 15 },
{ keyone:'a', keytwo: 'anna', keythree: 22, keyfour: 15 },
{ keyone:'s', keytwo: 'anna', keythree: 10, keyfour: 15 },
{ keyone:'v', keytwo: 'anna', keythree: 7, keyfour: 15 }
],
b: [
{ keyone:'f', keytwo: 'any', keythree: 45, keyfour: 100 },
{ keyone:'b', keytwo: 'any', keythree: 146, keyfour: 100 },
{ keyone:'t', keytwo: 'any', keythree: 23, keyfour: 100 },
{ keyone:'h', keytwo: 'any', keythree: 11, keyfour: 100 }
]
};
I want to assign ranks to each object, based on values of keythree
and keyfour
, within the groups as well as within the entire data set. How would I do it?
我想根据keythree和keyfour的值,在组内以及整个数据集中为每个对象分配排名。我该怎么办?
Update: I have depicted the ranks in my code above.
更新:我在上面的代码中描述了排名。
Resultant object:
结果对象:
var data = {
a: [
{ keyone:'c', keytwo: 'anna', keythree: 21, keyfour: 15, rankgroup: 3, rankall: 4 },
{ keyone:'a', keytwo: 'anna', keythree: 22, keyfour: 15, rankgroup: 4, rankall: 5 },
{ keyone:'s', keytwo: 'anna', keythree: 22, keyfour: 15, rankgroup: 2, rankall: 2 },
{ keyone:'v', keytwo: 'anna', keythree: 7, keyfour: 15, rankgroup: 1, rankall: 1 }
],
b: [
{ keyone:'f', keytwo: 'any', keythree: 45, keyfour: 100 },
{ keyone:'b', keytwo: 'any', keythree: 146, keyfour: 100 },
{ keyone:'t', keytwo: 'any', keythree: 23, keyfour: 100 },
{ keyone:'h', keytwo: 'any', keythree: 11, keyfour: 100 }
]
};
I am using lodash
. My idea is to first sort the array based on those keys, then loop over the original object, insert the sorted index by comparing another key. This is what I have tried:
我正在使用lodash。我的想法是首先根据这些键对数组进行排序,然后遍历原始对象,通过比较另一个键来插入排序的索引。这是我尝试过的:
var keys = Object.keys(data);
var result = {};
var numkeys;
for(var i=0; i
How would I do it? My logic seems too complex and the set
method does not update the original object by key but adds a new entry after the main object.
我该怎么办?我的逻辑看起来太复杂了,set方法不会按键更新原始对象,而是在主对象之后添加一个新条目。
Update: Notice the duplicate occurrence of 22
for the object a
. This leads to an issue when assigning ranks, since indexOf
will always return the index of the first occurrence, hence the second occurrence will never have an index assigned to it and hence the value will be undefined.
更新:注意对象a的重复出现22。这导致在分配排名时出现问题,因为indexOf将始终返回第一次出现的索引,因此第二次出现将永远不会为其分配索引,因此该值将是未定义的。
2 个解决方案