如果我有一个对象数组
[
{name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
{name: 'Bob', count: 6, isunique: false, occupation: 'carpenter'},
{name: "John", count: 9, isunique: false, occupation: "barber"}
]
(这个数组很大),我想确定哪些职业是唯一的,并且在那个条件下返回一个新数组,其中只有boolean isunique被改变如下:
[
{name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
{name: 'Bob', count: 6, isunique: false, occupation: 'carpenter'},
{name: "John", count: 9, isunique: true, occupation: "barber"}
]
这有可能在大型数组的Javascript中有效吗?我在这里完全不知所措。
答案 0 :(得分:1)
您可以迭代数组并根据是否更改isunique
属性,其他任何对象具有相同的职业,例如
arr.forEach(function(item) {
item.isunique = !arr.some(function(item2) {
return item !== item2 && item.occupation === item2.occupation;
});
});
var arr = [
{name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
{name: 'Bob', count: 6, isunique: false, occupation: 'carpenter'},
{name: "John", count: 9, isunique: false, occupation: "barber"}
]
arr.forEach(function(item) {
item.isunique = !arr.some(function(item2) {
return item !== item2 && item.occupation === item2.occupation;
});
});
document.body.innerHTML = '<pre>' + JSON.stringify(arr, null, 4) + '</pre>'
&#13;
答案 1 :(得分:1)
一个选项是:
var count = data.reduce(function(ret, el) {
ret[el.occupation] = (ret[el.occupation] || 0) + 1;
return ret;
}, {});
data.forEach(function(el) { el.isunique = count[el.occupation] === 1; });