I
I
Ilkhomjon Matazimov2020-04-27 19:55:03
PHP
Ilkhomjon Matazimov, 2020-04-27 19:55:03

How to filter an array by hasOwnProperty?

Good day!
I have an array where there are sub-arrays with a "last_seen" field.
I need to check that if there is no "last_seen" subarray anywhere in the array, then execute some code.

Arrays and subarrays:
5ea70e38e8d2f624066916.png

For if I check like this:

if($humans.hasOwnProperty('last_seen')) {
    return $humans.last_seen.time < (time - $hours)
}


Now I need to check: if there is no last_seen field everywhere, then //code

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-04-27
@mr_qpdb

Option 1 :

const $humans = await data.response.items;

if($humans.some(entry => entry.hasOwnProperty('last_seen'))) {
    // Всё еще массив, так что надо еще найти тот элемент, в котором есть этот ключ
} else {
    // Всё еще массив
}

Option 2 :
const $humans = await data.response.items;
const $human = $humans.find(entry => entry.hasOwnProperty('last_seen'));

if($human !== undefined) {
    // Первый элемент из массива с ключём last_seen
} else {
    // Какой-то код
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question