Check if javascript object is inside an existing array

别等时光非礼了梦想. 提交于 2019-12-23 06:37:07

问题


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



回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!