Javascript 基于过滤值的删除
我有一个带有目录和频率(目录的清理频率)的已解析的_JSON 如果所有is子目录频率都设置为“not”,我想删除该部分 例如:Javascript 基于过滤值的删除,javascript,ecmascript-6,lodash,Javascript,Ecmascript 6,Lodash,我有一个带有目录和频率(目录的清理频率)的已解析的_JSON 如果所有is子目录频率都设置为“not”,我想删除该部分 例如: [ { label: 'Offices', rows: [ { freq: '1w'},{ freq: '2w'},{ freq: 'not'} ] }, { label: 'Kitchen and community areas – Extras', rows: [ { freq: 'not'},{ freq: 'not'},{ freq: '
[ { label: 'Offices',
rows: [ { freq: '1w'},{ freq: '2w'},{ freq: 'not'} ] },
{ label: 'Kitchen and community areas – Extras',
rows: [ { freq: 'not'},{ freq: 'not'},{ freq: 'not'} ]
},
]
在这种情况下,应删除标有“厨房和社区区域-额外服务”的部分
我通过以下代码实现了这一点:
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);
}
});
});
但是我想用ES6方法重构它,比如filter()
,并且只通过mapped\u节进行映射
我一直在努力,但被困在这里:
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))
);
});
任何帮助都将不胜感激。谢谢大家! 让我知道它是否有效
let arr = [ { label: 'Offices',
rows: [ { freq: '1w'},{ freq: '2w'},{ freq: 'not'} ] },
{ label: 'Kitchen and community areas – Extras',
rows: [ { freq: 'not'},{ freq: 'not'},{ freq: 'not'} ]
},
]
arr.filter(ar => {
let rowCount = 0;
ar.rows.forEach(row => {
row.freq === 'not' ? rowCount++: rowCount;
})
return rowCount !== ar.rows.length
})
console.log(arr);
您可以运行not代码>在具有如下函数的元素行上:
const myList=[
{
标签:'办公室',
行:[{freq:'1w'},{freq:'2w'},{freq:'not'}]
},
{
标签:“厨房和社区区域-额外服务”,
行:[{freq:'not'},{freq:'not'},{freq:'not'}]
},
]
const result=myList.filter(el=>!el.rows.every(r=>r.freq==='not'))
console.log(result)
组合.find
和.some
let数据=[{
标签:'办公室',
行:[{
频率:“1w”
}, {
频率:2w
}, {
频率:'不'
}]
},
{
标签:“厨房和社区区域-额外服务”,
行:[{
频率:'不'
}, {
频率:'不'
}, {
频率:'不'
}]
}
];
const result=\.filter(数据,项=>\.some(item.rows,(x)=>x.freq!=='not'))
console.log({
结果
});代码>