-3

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;
}
14

2 Answers 2

2

You could use the in operator for a check of a property in an object.

The in operator returns true 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))

Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.