问题
I'm wanting to know how to check if an object still exists in an array
var a = [{ "id": 1, "name": "Jeffery" }, { "id": 2, "name": "Jimmy" }]
I'm trying to find if Jeffery
is still in this array:
var obj = { "names": { "Jeffery": { "age": 43, "job": "Doctor" }, "Jimmy": { "age": 23, "job": "Developer" } } };
I've attempted to use this code which brings no luck. Am I doing anything wrong?
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
回答1:
You could use the in operator for a check of a property in an object.
The
in
operator returnstrue
if the specified property is in the specified object.
function contains(name, obj) {
return name in obj.names;
}
var obj = { names: { Jeffery: { age: 43, job: "Doctor" }, Jimmy: { age: 23, job: "Developer" } } };
console.log(contains('Jeffery', obj));
console.log(contains('Foo', obj))
回答2:
With the function contains
you can check the desired name: 'Jeffery'
is in the the object and also in the array:
var a = [{ "id": 1, "name": "Jeffery" }, { "id": 2, "name": "Jimmy" }],
obj = { "names": { "Jeffery": { "age": 43, "job": "Doctor" }, "Jimmy": { "age": 23, "job": "Developer" } } };
function contains(name, a, obj) {
return obj.names[name] && a.filter(o => o.name === name) ? true : false;
}
console.log(contains('Jeffery', a, obj));
console.log(contains('Jimmy', a, obj));
console.log(contains('Foo', a, obj));
来源:https://stackoverflow.com/questions/41197554/check-if-javascript-object-is-inside-an-existing-array