Skip to content

pick

从对象中只选择所需的属性

276 bytes
since v12.1.0

使用方法

给定一个对象和对象中键的列表,返回一个只包含给定键的新对象。

import * as _ from "radashi";
const fish = {
name: "Bass",
weight: 8,
source: "lake",
brackish: false,
};
_.pick(fish, ["name", "source"]); // => { name, source }

谓词函数

pick 函数也可以接受谓词函数作为过滤参数。这允许比简单的键包含或排除更复杂的过滤逻辑。

import * as _ from "radashi";
const source = { a: 1, b: 2, c: 3, d: 4 };
_.pick(source, (value, key) => {
return value % 2 === 0; // 只包含偶数值
});
// => { b: 2, d: 4 }

不安全的谓词函数

// 演示 `_.pick` 回调中 `key` 和 `value` 类型潜在不准确性的示例
import * as _ from "radashi";
interface User {
name: string;
age: number;
}
function getUserDetails(user: User) {
return _.pick(user, (value, key) => {
// TypeScript认为 `key` 是 'name' | 'age',但在运行时
// 它可能是 'email'
if (key === "name" || key === "age") {
console.log(key, "=", value);
} else {
// TypeScript认为这永远不会运行,但它确实会运行。
console.log("Unexpected key:", key);
}
});
}
// 在运行时,函数可能接收具有更多属性的对象
const runtimeUser = {
name: "John",
age: 30,
// 这个属性未在User类型中列出:
email: "john@example.com",
};
getUserDetails(runtimeUser);
// 记录以下内容:
// name = John
// age = 30
// Unexpected key: email