在 ng-repeat 中按 属性 查找重复项并向其添加 属性
Find duplicates by property in ng-repeat and add property to them
我在我的控制器中定义了一个对象,该对象在 ng-repeater 中输出。它看起来有点像这样:
var _this = this;
_this.items = [
{
"Entityid": "300", "Name": "Lorem ipsum #1"
},
{
"Entityid": "100", "Name": "Lorem ipsum #2"
},
{
"Entityid": "500", "Name": "Lorem ipsum #3"
},
{
"Entityid": "300", "Name": "Lorem ipsum #4"
}
]
问题:如何遍历它并在所有包含重复 "Entityid" 的项目上设置 "flag"?所以它看起来像这样:
var _this = this;
_this.items = [
{
"Entityid": "300", "Name": "Lorem ipsum #1", "IsDuplicated": true
},
{
"Entityid": "100", "Name": "Lorem ipsum #2", "IsDuplicated": false
},
{
"Entityid": "500", "Name": "Lorem ipsum #3", "IsDuplicated": false
},
{
"Entityid": "300", "Name": "Lorem ipsum #4", "IsDuplicated": true
}
]
如果它更容易的话,我已经在项目中包含了下划线。
检查一次并获取实体 ID 的计数并存储在对象中,然后再次检查并通过执行计数查找
为 属性 添加适当的值
var tmp={};
_this.items.forEach(function(item){
if(!tmp[item.Entityid]){
tmp[item.Entityid] = 0;
}
tmp[item.Entityid] ++;
});
_this.items.forEach(function(item){
item.IsDuplicated = tmp[item.Entityid] > 1;
});
您可以使用下划线 countBy to county the number of items with the same id and then extend 每个项目与 IsDuplicated 属性:
var counts = _.countBy(items, 'Entityid');
_.each(items, item => _.extend(item, { IsDuplicated: counts[item.Entityd] > 1}))
甚至更短:
_.each(items, item => item.IsDuplicated == (counts[item.Entityd] > 1));
我在我的控制器中定义了一个对象,该对象在 ng-repeater 中输出。它看起来有点像这样:
var _this = this;
_this.items = [
{
"Entityid": "300", "Name": "Lorem ipsum #1"
},
{
"Entityid": "100", "Name": "Lorem ipsum #2"
},
{
"Entityid": "500", "Name": "Lorem ipsum #3"
},
{
"Entityid": "300", "Name": "Lorem ipsum #4"
}
]
问题:如何遍历它并在所有包含重复 "Entityid" 的项目上设置 "flag"?所以它看起来像这样:
var _this = this;
_this.items = [
{
"Entityid": "300", "Name": "Lorem ipsum #1", "IsDuplicated": true
},
{
"Entityid": "100", "Name": "Lorem ipsum #2", "IsDuplicated": false
},
{
"Entityid": "500", "Name": "Lorem ipsum #3", "IsDuplicated": false
},
{
"Entityid": "300", "Name": "Lorem ipsum #4", "IsDuplicated": true
}
]
如果它更容易的话,我已经在项目中包含了下划线。
检查一次并获取实体 ID 的计数并存储在对象中,然后再次检查并通过执行计数查找
为 属性 添加适当的值var tmp={};
_this.items.forEach(function(item){
if(!tmp[item.Entityid]){
tmp[item.Entityid] = 0;
}
tmp[item.Entityid] ++;
});
_this.items.forEach(function(item){
item.IsDuplicated = tmp[item.Entityid] > 1;
});
您可以使用下划线 countBy to county the number of items with the same id and then extend 每个项目与 IsDuplicated 属性:
var counts = _.countBy(items, 'Entityid');
_.each(items, item => _.extend(item, { IsDuplicated: counts[item.Entityd] > 1}))
甚至更短:
_.each(items, item => item.IsDuplicated == (counts[item.Entityd] > 1));