我有一个像这样的对象数组:
[{ value: 40,
username: 'Name 1',
id: 'high'
},
{ value: 30,
username: 'Name 2',
id: 'low',
},
{ value: 60,
username: 'Name 1',
id: 'low',
},
{ value: 50,
username: 'Name 2',
id: 'high'
}]
我想比较具有相同 username
键的对象,并在对象具有属性 id: low
及其 值
的情况下返回 false高于 id
设置为 high
的任何相应对象。
因此,对于此对象,将返回 false,因为第三个对象的 id 为 low
,并且它的值比具有相同用户名的对应对象更高high
在其 id 中。
目前我正在将数组过滤为两个单独的数组,如下所示。
const higherTest = test.filter(item => item.id === 'high');
const lowerTest = test.filter(item => item.id === 'low');
然后使用嵌套 for 循环比较两者,但这似乎过多,我想知道是否有更干净的方法?
最佳答案
您可以使用已访问名称的哈希表并存储低值和高值。如果找到一对,请检查值并返回检查结果。
此方法使用短路并返回第一个找到的低>高
条件。
var data = [{ value: 40, username: 'Name 1', id: 'high' }, { value: 30, username: 'Name 2', id: 'low' }, { value: 60, username: 'Name 1', id: 'low' }, { value: 50, username: 'Name 2', id: 'high' }],
result = !data.some((m => ({ value, username, id }) => {
const user = m[username] = m[username] || {};
user[id] = value;
return 'high' in user && 'low' in user && user.low > user.high;
})({}));
console.log(result);
关于javascript - 比较一个 JavaScript 对象数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60619645/