var obj = {
111: {
user_id: 111,
user_name: "user111",
isActive: 0
},
112: {
user_id: 112,
user_name: "use112",
isActive: 1
},
113: {
user_id: 113,
user_name: "use113",
isActive: 0
},
...
}
I want to filter all ("isActive" === 0)
but keep the key set the same (which is equal to the user id) when returning the newObj:
newObj = {
111: {
user_id: 111,
user_name: "user111",
isActive: 0
},
113: {
user_id: 113,
user_name: "use113",
isActive: 0
},
...
}
This is what I have now:
let newObj = Object.values(obj).filter( user => ( (obj.isActive === 0)));
which returns indexed keys
.forEach()
is a must).The truly FP way would be reduce
with repeated object spread:
const filtered = Object.values(obj).reduce((p, e) => (!e.isActive ? {...p, [e.user_id]: e} : p), {});
const obj = {
111: {
user_id: 111,
user_name: "user111",
isActive: 0
},
112: {
user_id: 112,
user_name: "use112",
isActive: 1
},
113: {
user_id: 113,
user_name: "use113",
isActive: 0
}
};
const filtered = Object.values(obj).reduce((p, e) => (!e.isActive ? {...p, [e.user_id]: e} : p), {});
console.log(filtered);
.as-console-wrapper {
max-height: 100% !important;
}
That creates lots of unnecessary temporary objects, but adheres to FP principles (I think, I'm not "deep" on FP :-)) by not modifying objects in place.
Bending the rules a bit, we might modify a single object rather than creating lots of temporaries:
const filtered = Object.values(obj).reduce((newObj, e) => {
if (!e.isActive) {
newObj[e.user_id] = e;
}
return newObj;
}, {});
const obj = {
111: {
user_id: 111,
user_name: "user111",
isActive: 0
},
112: {
user_id: 112,
user_name: "use112",
isActive: 1
},
113: {
user_id: 113,
user_name: "use113",
isActive: 0
}
};
const filtered = Object.values(obj).reduce((newObj, e) => {
if (!e.isActive) {
newObj[e.user_id] = e;
}
return newObj;
}, {});
console.log(filtered);
.as-console-wrapper {
max-height: 100% !important;
}
(That can be written in fewer characters by abusing the comma operator, but it's less maintainable and harder to read.)
Without the FP restriction, I'd just use a loop:
const filtered = {};
for (const e of Object.values(obj)) {
if (!e.isActive) {
filtered[e.user_id] = e;
}
}
const obj = {
111: {
user_id: 111,
user_name: "user111",
isActive: 0
},
112: {
user_id: 112,
user_name: "use112",
isActive: 1
},
113: {
user_id: 113,
user_name: "use113",
isActive: 0
}
};
const filtered = {};
for (const e of Object.values(obj)) {
if (!e.isActive) {
filtered[e.user_id] = e;
}
}
console.log(filtered);
.as-console-wrapper {
max-height: 100% !important;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With