我想用“ some”检查对象数组中是否存在对象值。
我只能发现对象爱好存在于带有“ some”的数组中
"users": [
{
"type": "User",
"name": "Sarah",
"hobbys":
{
first: "something1",
second: "something2"
}
}
]
users.some(item => item.hobbys); // true
我要检查“爱好”中的“第一个”值是否存在。
答案 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