Reputation: 63
What is the best way in JavaScript to go over array of object and check if an certain value already exist in one of the property of the array objects? For example: I have array of objects as follow: [{name:"team1",members:3},{name:"bestteam",members:4}] Now I want to add a new object but I want to check that this object property "name" do not exist in the array before adding it
Upvotes: 1
Views: 17300
Reputation: 876
You can use simple loops. Here is function which should help you to find out if key value is in array.
function keyExist(value, array) {
for(var i in array) {
for(var k in array[i])
if(array[i][k] === value) {
console.log(value + ' is in array!');
return true;
}
}
return false;
}
As for you example you can change second loop
for(var k in array[i])
if(k === value) { return true; }
to
if(array[i].name === value) { return true; }
Upvotes: 1
Reputation: 426
Try this
function checkIfNameExists(arr, newName) {
return arr.some(function(e) {
return e.name === newName;
});
}
where arr is your array and newName is the name to check.
You could also make it less ad hoc by passing the property to compare as a parameter, like so
function checkIfNameExists(arr, prop, newVal) {
return arr.some(function(e) {
return e[prop] ? e[prop] === newVal : false;
});
}
Upvotes: 3
Reputation: 386522
You can iterate over the array and iterate over the keys of the array and check if some properties have the wanted value.
var data = [{ prop1: 'one', prop2: 'two' }, { prop3: 'three', prop4: 'four' }];
function find(v, data) {
data.forEach(function (a, i) {
Object.keys(a).forEach(function (k) {
if (a[k] === v) {
document.write(v + ' found in [' + i + '].' + k);
}
});
});
}
find('three', data);
Upvotes: 1
Reputation: 2771
assuming you say an object equals an object if and only if they have the exact same elements and values for each element:
var map = {};
for (var i = 0; i < arr.length; i++) {
var index = JSON.stringify(arr[i]);
if (!map[index]) {
map[index] = 1;
} else {
map[index]++;
}
}
for (var key in map) {
if (map[key] > 1) {
console.log ('duplicate found for:');
console.log (JSON.parse (key));
}
}
simply define an array "arr" with some objects and check it out
Upvotes: 1
Reputation: 1648
I have no time to respond but here from my previous code maybe some will optimize it...
function JSONRemoveDuplicates(JSONDATA) {
var uniqueNames = [];
$.each(JSONDATA, function (i, el) {
if (!existInJSON(uniqueNames, el) > 0) { uniqueNames.push(el); }
});
return uniqueNames;
}
function existInJSON(jsondata, el) {
var ret = 0;
$(jsondata).each(function (index, data) {
if (data.id == el.id)
ret++;
})
return ret > 0;
}
Upvotes: 0