Reputation: 2587
I have a normalized Object like this (for example):
const raw = {
1: { foo: 1, bar: 1, flag: 0 },
4: { foo: 4, bar: 4, flag: 1 },
11: { foo: 11, bar: 11, flag: 0 },
...
}
I wanna delete values which have flag: 1
.
{
1: { foo: 1, bar: 1, flag: 0 },
11: { foo: 11, bar: 11, flag: 0 },
...
}
How can I do this immutably?
Upvotes: 1
Views: 93
Reputation: 68943
You can use Object.values()
and Array.prototype.filter()
var obj = {
1: { foo: 1, bar: 1, flag: 0 },
2: { foo: 2, bar: 2, flag: 1 },
3: { foo: 3, bar: 3, flag: 0 }
}
var newobj = Object.assign({}, Object.values(obj).filter(o => o.flag != 1));
console.log(newobj);
You can use reduce()
to keep the keys:
var obj = {
1: { foo: 1, bar: 1, flag: 0 },
2: { foo: 2, bar: 2, flag: 1 },
3: { foo: 3, bar: 3, flag: 0 }
}
var newobj = Object.keys(obj).reduce((a,c) => {
if(obj[c].flag != 1)
a[c] = obj[c]; return a;
},{});
console.log(newobj);
Upvotes: 6
Reputation: 39332
You can use Object.keys()
and .reduce()
methods:
let data = {
1: { foo: 1, bar: 1, flag: 0 },
2: { foo: 2, bar: 2, flag: 1 },
3: { foo: 3, bar: 3, flag: 0 }
};
let result = Object.keys(data).reduce((a, c) => {
if(data[c].flag !== 1)
a[c] = Object.assign({}, data[c]);
return a;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1
Reputation: 1822
You can object filtering by lodashjs. https://lodash.com/docs/#filter
_.filter(obj, o => !o.flag);
Upvotes: 2