E
E
ekzotika2020-07-28 17:10:30
JavaScript
ekzotika, 2020-07-28 17:10:30

Why is the nested array not being filtered?

I'm trying to filter the children element of an array, but I don't understand how I can refer specifically to children. So far, I only have a top-level filter.

Array:

options: [
                    {name: 'Выход детали из строя в процессе эксплуатации', value: null,
                        children: [{name: 'Увеличение зазора, люфт (дробь/стуки)', value: 53},
                                    {name: 'Обрыв детали', value: 54}]},

                    {name: 'Поломка при установке', value: null},

                    {name: 'Брак до установки', value: null,
                        children: [{name: 'Недокомплект', value: 55},
                                    {name: 'Заводской брак (замятия, отсутствие резьбы, пробой пыльника и т.д.)',
                                        value: 56}]},

         ],


List output:

<div v-if="areOptionsVisible"
         :style="{maxHeight: maxHeight, overflow: 'auto', zIndex: zIndex}"
         class="w-autocomplete__items">
        <div v-for="option in filteredOptions" class="w-autocomplete__item_first" >
            {{ option.name }}

                <div v-for="item in option.children" class="w-autocomplete__item"
                    :class="{'w-autocomplete__item_active': currentIndex === item}"
                    @mouseenter="setActive(item)"
                     @keyup.up="changeCurrent('up', item)"
                     @keyup.down="changeCurrent('down', item)"
                     @click="doChoose(item)">
                    {{ item.name }}
                </div>
        </div>
    </div>


The filter itself:

computed: {
        filteredOptions(){
            return this.options.filter(elem => {
                return elem.name.toLowerCase().includes(this.searchText.toLowerCase());
            });
        },
    },

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-07-28
@ekzotika

filteredOptions() {
    return filter(this.options, new RegExp(this.searchText, 'gi'));
},

And the function itself filter:
const filter = (data, needle, store = []) => {
    for (const entry of data) {
        const branch = {
            ...entry,
            children: []
        };
        const isValid = needle.test(entry.name);

        if (entry.hasOwnProperty('children') && entry.children.length > 0) {
            filter(entry.children, needle, branch.children);

            if (branch.children > 0 || isValid) {
                store.push(branch);
            }
        } else {
            if (isValid) {
                store.push(branch);
            }
        }
    }

    return store;
};

Example

const options = [
    {
        name: 'Выход детали из строя в процессе эксплуатации',
        value: null,
        children: [
            {
                name: 'Увеличение зазора, люфт (дробь/стуки)',
                value: 53
            },
            {
                name: 'Обрыв детали',
                value: 54
            }
        ]
    },
    {
        name: 'Поломка при установке',
        value: null
    },
    {
        name: 'Брак до установки',
        value: null,
        children: [
            {
                name: 'Недокомплект',
                value: 55
            },
            {
                name: 'Заводской брак (замятия, отсутствие резьбы, пробой пыльника и т.д.)',
                value: 56
            }
        ]
    }
];

console.log(filter(options, new RegExp('детали', 'gi')));
/*
[
    {
        name: 'Выход детали из строя в процессе эксплуатации',
        value: null,
        children: [ { name: 'Обрыв детали', value: 54, children: [] } ]
    }
]
*/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question