如何在javascript中过滤此动态对象? 对于下面的数据对象是动态的,我想过滤页面是否相同但是hasPlan是否为假。
data = [ { page: 1, hasPlan: false },
{ page: 2, hasPlan: false },
{ page: 3, hasPlan: false },
{ page: 4, hasPlan: false },
{ page: 4, hasPlan: true },
{ page: 5, hasPlan: false },
{ page: 6, hasPlan: false } ];
预期结果:
data = [ { page: 1, hasPlan: false },
{ page: 2, hasPlan: false },
{ page: 3, hasPlan: false },
{ page: 4, hasPlan: true },
{ page: 5, hasPlan: false },
{ page: 6, hasPlan: false } ];
答案 0 :(得分:0)
首先制作地图
map = {};
data.forEach( function(item){
map[ String(item.page) ] = map[ String(item.page) ] || item.hasPlan; //notice that if map[ String(item.page) ] is already true, then item.hasPlan is not set.
});
然后迭代相同的地图并获得输出
var output = Object.keys(map).map( s => ({ page : s , hasPlan : map[s] }) )
<强>演示强>
var data = [ { page: 1, hasPlan: false },
{ page: 2, hasPlan: false },
{ page: 3, hasPlan: false },
{ page: 4, hasPlan: false },
{ page: 4, hasPlan: true },
{ page: 5, hasPlan: false },
{ page: 6, hasPlan: false } ];
var map = {};
data.forEach( function(item){
map[ String(item.page) ] = map[ String(item.page) ] || item.hasPlan;
})
var output = Object.keys(map).map( s => ({ page : s , hasPlan : map[s] }) );
console.log( output );
答案 1 :(得分:0)
您可以首先获得包含所有hasPlan
页面的对象,然后过滤数据。
var data = [{ page: 1, hasPlan: false }, { page: 2, hasPlan: false }, { page: 3, hasPlan: false }, { page: 4, hasPlan: false }, { page: 4, hasPlan: true }, { page: 5, hasPlan: false }, { page: 6, hasPlan: false }],
hasPlan = {},
result;
data.forEach(function (o) {
if (o.hasPlan) {
hasPlan[o.page] = true;
}
});
result = data.filter(function (o) {
return !hasPlan[o.page] || o.hasPlan;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6
var data = [{ page: 1, hasPlan: false }, { page: 2, hasPlan: false }, { page: 3, hasPlan: false }, { page: 4, hasPlan: false }, { page: 4, hasPlan: true }, { page: 5, hasPlan: false }, { page: 6, hasPlan: false }],
hasPlan = new Set(data
.filter(o => o.hasPlan)
.map(o => o.page)
),
result = data.filter(o => !hasPlan.has(o.page) || o.hasPlan);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
我的approch将是:
var data = [ { page: 1, hasPlan: false },
{ page: 2, hasPlan: false },
{ page: 3, hasPlan: false },
{ page: 4, hasPlan: false },
{ page: 4, hasPlan: true },
{ page: 5, hasPlan: false },
{ page: 6, hasPlan: false } ];
data.forEach(d => {
if (d.hasPlan){
data.filter(d2 => d2.page === d.page).forEach((d3, i) => {
if(d3.hasPlan === false) {
data.splice(data.indexOf(d3), 1);
}
});
}
});