javascript - 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!
解决方案
您可以在具有如下功能的元素行上运行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)
全部为freq
s 的项目not
被过滤掉。
推荐阅读
- python - SAP UnicodeDecodeError:“utf-8”编解码器无法解码位置 2-3 中的字节:调用 RFC_READ_TABLE 时数据意外结束
- matlab - 带有 for 循环的 MATLAB add_line 给出了无效的 Simulink 对象名称错误
- c# - 我可以用另一种语言连接到数据库吗
- java - 如何使用 prometheus java 库执行 PromQL 查询?
- c++ - 如何从已经存在的遗留列表创建 boost::intrusive::list?
- macos - NSButton 对 +/- 圆角,如 Finder?
- sql - 在 Sql Server 中向表中添加列需要很长时间
- postgresql - 对这个简单 SQL 的建议
- python - 图像调整大小时 Keras 图像分类预测误差
- reactjs - 在“SurveySettingTypes”类型上找不到具有“字符串”类型参数的索引签名