Reputation: 89
I want to check if a object value exist in a array of objects with "some".
I only can find that the object hobbys exist in the array with "some"
"users": [
{
"type": "User",
"name": "Sarah",
"hobbys":
{
first: "something1",
second: "something2"
}
}
]
users.some(item => item.hobbys); // true
I want to check if "first" value in "hobbys" exist.
Upvotes: 2
Views: 95
Reputation: 99
function will return true if it has value else false
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
Upvotes: 0
Reputation: 2228
const users = [{
"type": "User",
"name": "Sarah",
"hobbys": {
first: "somethig1",
second: "something2"
}
}];
const hobbyExists = users.some(({ hobbys }) => (typeof hobbys === 'object' && hobbys['first']));
console.log(hobbyExists);
Upvotes: 0
Reputation: 28455
You can try following assuming hobbys
will always be an object
and first
will not have any falsy values.
let users = [{"type": "User","name": "Sarah","hobbys": {"first": "something1","second": "something2"}}];
console.log(users.some(item => item.hobbys && item.hobbys.first)); // true
Upvotes: 1
Reputation: 2090
You can use "key" in obj
also to check if a key is part if 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);
Alternate and fast way to check is
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);
Upvotes: 0
Reputation: 370729
Check if the hobbys
is an object and has an own property of 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);
Upvotes: 1