跳到主要内容

toPlainObject()

function toPlainObject(value): Record<string, any>;

Defined in: object/toPlainObject.ts:20

将任意值转换为普通对象,只保留自有属性 通过遍历对象的可枚举属性,创建一个新的普通对象

Parameters

ParameterTypeDescription
valueany要转换的值

Returns

Record<string, any>

包含所有自有属性的普通对象

Examples

const obj = Object.create({ inherited: 'value' });
obj.own = 'own value';
toPlainObject(obj); // 返回 { own: 'own value' }(只保留自有属性)
toPlainObject('string'); // 返回 {}(字符串没有自有属性)
toPlainObject(null); // 返回 {}(null/undefined 返回空对象)
toPlainObject([1, 2, 3]); // 返回 { '0': 1, '1': 2, '2': 3 }(数组转换为对象)
**Note:** 使用 Object.prototype.hasOwnProperty 确保只复制自有属性
**Note:** 对于非对象值,返回空对象
**Note:** 不会复制原型链上的属性