我有一个带有目录和频率(目录的清洗频率)的parsed_JSON。
如果所有子目录频率都设置为“ not”,我想删除该部分。
例如:
[ { 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);
}
});
});
但是我想使用filter()
之类的ES6方法并仅通过mapped_sections
进行映射来重构它
我一直在尝试,但是被卡在这里:
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))
);
});
任何帮助将不胜感激。谢谢!
答案 0 :(得分:2)
您可以使用every
函数在元素行上运行 not !
,如下所示:
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
个not
的项目都被过滤掉。
答案 1 :(得分:0)
让我知道它是否有效
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);
答案 2 :(得分:0)
结合_.find
和_.some
let data = [{
label: 'Offices',
rows: [{
freq: '1w'
}, {
freq: '2w'
}, {
freq: 'not'
}]
},
{
label: 'Kitchen and community areas – Extras',
rows: [{
freq: 'not'
}, {
freq: 'not'
}, {
freq: 'not'
}]
}
];
const result = _.filter(data, item => _.some(item.rows, (x) => x.freq !== 'not'))
console.log({
result
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>