1.38.0filterObject
Creates a new object containing the properties that satisfy a predicate.
filterObject(object, predicate):Partial<T>Parameters
objectTrequiredThe object whose properties should be filtered.
predicate(value: T[keyof T], key: keyof T, object: T) => booleanrequiredA function called for each own enumerable string-keyed property. It receives the property value, key, and original object. Returning true includes the property in the result.
Returns
Partial<T>Returns a new object containing only the properties for which the predicate returned true.
Examples
Basic usage
Keeps only properties whose values are numbers.
const result = filterObject(
{
name: "Alice",
age: 25,
score: 90,
},
(value) => typeof value === "number",
);
console.log(result);
// {
// age: 25,
// score: 90
// }Filter by key
The predicate can inspect the property key.
const result = filterObject(
{
name: "Alice",
age: 25,
active: true,
},
(_value, key) => key !== "active",
);
console.log(result);
// {
// name: "Alice",
// age: 25
// }Filter by value
The predicate receives each property's value.
const result = filterObject(
{
a: 5,
b: 12,
c: 20,
},
(value) => typeof value === "number" && value > 10,
);
console.log(result);
// {
// b: 12,
// c: 20
// }Using the original object
The third predicate argument is the original object.
const result = filterObject(
{
min: 10,
max: 20,
value: 15,
},
(value, key, object) => {
if (key === "value") {
return (
typeof value === "number" &&
value >= object.min &&
value <= object.max
);
}
return false;
},
);
console.log(result);
// {
// value: 15
// }No matches
If the predicate returns false for every property, an empty object is returned.
const result = filterObject(
{
a: 1,
b: 2,
},
() => false,
);
console.log(result);
// {}All matches
Returning true for every property copies all enumerable own string-keyed properties.
const result = filterObject(
{
name: "Alice",
age: 25,
},
() => true,
);
console.log(result);
// {
// name: "Alice",
// age: 25
// }Original object is unchanged
The function creates a separate result object and does not modify the input object.
const original = {
name: "Alice",
age: 25,
};
const result = filterObject(
original,
(value) => typeof value === "string",
);
console.log(original);
// {
// name: "Alice",
// age: 25
// }
console.log(result);
// {
// name: "Alice"
// }
console.log(result === original);
// falseInherited properties
Inherited properties are not processed because the implementation uses Object.keys.
const parent = {
inherited: true,
};
const object = Object.create(parent);
object.own = true;
const result = filterObject(
object,
() => true,
);
console.log(result);
// {
// own: true
// }