首页 > 解决方案 > removing based on filtered value

问题描述

I have a parsed_JSON with directories and frequencies(cleaning frequency of the directory).

I want to remove the section if all of is sub directory frequency is set to "not".

For example:

[ { label: 'Offices',
     rows: [ { freq: '1w'},{ freq: '2w'},{ freq: 'not'} ]  },
  { label: 'Kitchen and community areas – Extras',
    rows: [ { freq: 'not'},{ freq: 'not'},{ freq: 'not'} ] 
},
]

in this case the section labeled 'Kitchen and community areas – Extras' should be removed.

I achieved this with the following code:

  const mapped_sections      = _.map(parsed_json, section => ({
        label   : section.label,
        rows    : _.map(section.rows, row => _.merge({}, default_row, row)),
    }));

    const sections = _.forEach(mapped_sections, (section, i) => {
        let not_length_count = 0;
        _.forEach(section, (rows) => {
            _.forEach(rows, (row) => {
                if (row.freq === "not") {
                    not_length_count += 1;
                }
            });
            if (not_length_count === rows.length) {
                mapped_sections.splice(i, 1);
            }
        });
    });

But I want to refactor it with ES6 methods like filter() and by only mapping through mapped_sections

I've been trying but got stuck here:

const sections      = _.map(parsed_json, (section, i) => {
        const test = ((section.rows.filter(item => item.freq === "not"))
                && (section.rows.filter(item => item.freq === "not").length === section.rows.length)
            ? section.rows.slice(i, 1)
            : section.rows
        );
        return (
            section.label,
            _.map(test, row => _.merge({}, default_row, row))
        );
    });

Any help would be much appreciated. Thank you!

标签: javascriptecmascript-6lodash

解决方案


您可以在具有如下功能的元素行上运行not :!every

const myList = [
  {
    label: 'Offices',
    rows: [{ freq: '1w'},{ freq: '2w'},{ freq: 'not'}]
  },
  {
    label: 'Kitchen and community areas – Extras',
    rows: [{ freq: 'not'},{ freq: 'not'},{ freq: 'not'}] 
  },
]

const result = myList.filter(el => !el.rows.every(r => r.freq === 'not'))

console.log(result)

全部为freqs 的项目not被过滤掉。


推荐阅读