在对象数组JavaScript中查找对象值

时间:2019-05-10 09:07:00

标签: javascript arrays

我想用“ some”检查对象数组中是否存在对象值。

我只能发现对象爱好存在于带有“ some”的数组中

"users": [
   {
     "type": "User",
     "name": "Sarah",
     "hobbys":
      {
        first: "something1",
        second: "something2"
      }
   }
]

users.some(item => item.hobbys); // true

我要检查“爱好”中的“第一个”值是否存在。

5 个答案:

答案 0 :(得分:1)

检查hobbys是否是一个对象,并具有first自己的属性:

const users = [{
  "type": "User",
  "name": "Sarah",
  "hobbys": {
    first: "something1",
    second: "something2"
  }
}];

const userWithFirstHobbyExists = users.some(({ hobbys }) => (
 typeof hobbys === 'object' && hobbys.hasOwnProperty('first')
));
console.log(userWithFirstHobbyExists);

答案 1 :(得分:1)

您可以尝试假设hobbys始终为object,而first则没有任何 fassy 值。

let users = [{"type": "User","name": "Sarah","hobbys": {"first": "something1","second": "something2"}}];

console.log(users.some(item => item.hobbys && item.hobbys.first)); // true

答案 2 :(得分:0)

您还可以使用"key" in obj来检查键是否是object的一部分。

const users = [{
  "type": "User",
  "name": "Sarah",
  "hobbys": {
    first: "something1",
    second: "something2"
  }
}];

const userWithFirstHobbyExists = users.some(({ hobbys }) => (
 typeof hobbys === 'object' && ('first' in hobbys )
));
console.log(userWithFirstHobbyExists);

另一种快速检查方法是

    const users = [{
      "type": "User",
      "name": "Sarah",
      "hobbys": {
        first: "something1",
        second: "something2"
      }
    }];

    const userWithFirstHobbyExists = users.some(({ hobbys }) => (
     typeof hobbys === 'object' && hobbys['first'] !== undefined
    ));
    console.log(userWithFirstHobbyExists);

答案 3 :(得分:0)

const users = [{
  "type": "User",
  "name": "Sarah",
  "hobbys": {
    first: "somethig1",
    second: "something2"
  }
}];

const hobbyExists = users.some(({ hobbys }) => (typeof hobbys === 'object' && hobbys['first']));
console.log(hobbyExists);

答案 4 :(得分:0)

如果函数的值为false,则返回true

let jData = {
    "users": [{
        "type": "User",
        "name": "Sarah",
        "hobbys": {
            "first": "something1",
            "second": "something2"
        }
    }]
};

function hasValue(data, obj, key) {
    return data.some(item => item[obj] && item[obj][key]);
}
console.log(hasValue(jData.users, 'hobbys', 'second')) //true
console.log(hasValue(jData.users, 'hobbys', 'first')) // true
console.log(hasValue(jData.users, 'test', 'first'))  //false