我有一个像这样的数组:
var myArray = [
{id: 1, entry_id: 1, name: 'test', email: 'foo@bar.com'},
{id: 2, entry_id: 1, name: 'test', email: 'bar@foo.com'},
{id: 3, entry_id: 2, name: 'test', email: 'foo@bar.com'},
{id: 4, entry_id: 2, name: 'test', email: 'bar@foo.com'},
{id: 5, entry_id: 3, name: 'test', email: 'joe@ocean.com'},
{id: 6, entry_id: 3, name: 'test', email: 'foo@bar.com'},
{id: 7, entry_id: 3, name: 'test', email: 'foo@bar.com'},
];
我需要用相同的“entry_id”和“name”来标记哪个元素是第一个,所以结果应该是这样的:
[
{id: 1, entry_id: 1, name: 'test', email: 'foo@bar.com', isFirst:true},
{id: 2, entry_id: 1, name: 'test', email: 'bar@foo.com', isFirst:false},
{id: 3, entry_id: 2, name: 'test', email: 'foo@bar.com', isFirst:true},
{id: 4, entry_id: 2, name: 'test', email: 'bar@foo.com', isFirst:false},
{id: 5, entry_id: 3, name: 'test', email: 'joe@ocean.com', isFirst:true},
{id: 6, entry_id: 3, name: 'test', email: 'foo@bar.com', isFirst:false},
{id: 7, entry_id: 3, name: 'test', email: 'foo@bar.com', isFirst:false},
];
我已经尝试过:
function updateArray() {
myArray.forEach((item, i) => {
item.isFirst = false;
myArray.forEach((item2, j) =>{
if (item.entry_id == item2.entry_id && item.name == item2.name && i < j ) {
item.isFirst = true;
} else if (!item.isFirst) {
item.isFirst = false;
}
})
})
return myArray;
}
我得到的结果如下:
[
{id: 1, entry_id: 1, name: 'test', email: 'foo@bar.com', isFirst:true},
{id: 2, entry_id: 1, name: 'test', email: 'bar@foo.com', isFirst:false},
{id: 3, entry_id: 2, name: 'test', email: 'foo@bar.com', isFirst:true},
{id: 4, entry_id: 2, name: 'test', email: 'bar@foo.com', isFirst:false},
{id: 5, entry_id: 3, name: 'test', email: 'joe@ocean.com', isFirst:true},
{id: 6, entry_id: 3, name: 'test', email: 'foo@bar.com', isFirst:true},
{id: 7, entry_id: 3, name: 'test', email: 'foo@bar.com', isFirst:false},
];
有没有比使用 2 个循环更好的方法?
感谢您的帮助!
链接到jsfiddle: https://jsfiddle.net/88p5p5oj/30/
最佳答案
您可以使用哈希表在单个循环中收集所需组的第一个标志。
var array = [{ id: 1, entry_id: 1, name: 'test', email: 'foo@bar.com' }, { id: 2, entry_id: 1, name: 'test', email: 'bar@foo.com' }, { id: 3, entry_id: 2, name: 'test', email: 'foo@bar.com' }, { id: 4, entry_id: 2, name: 'test', email: 'bar@foo.com' }, { id: 5, entry_id: 3, name: 'test', email: 'joe@ocean.com' }, { id: 6, entry_id: 3, name: 'test', email: 'foo@bar.com' }, { id: 7, entry_id: 3, name: 'test', email: 'foo@bar.com' }],
keys = ['entry_id', 'name'],
hash = Object.create(null);
array.forEach(o => {
var key = keys.map(k => o[k]).join('|');
o.isFirst = !hash[key];
hash[key] = true;
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何在 JavaScript 中的对象数组中标记具有重复属性的第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49760905/