JavaScript中Object对象提供了多种常用方法
1、Object.keys()
(1)、返回对象自身可枚举属性的键名数组
const obj = { name: "张三", age: 25 };
console.log(Object.keys(obj)); // 输出: ["name", "age"]
(2)、获取对象属性数量
const person = { name: "hahaha", age: 30 };
const size = Object.keys(person).length; // 2
2、Object.values()
(1)、返回对象自身可枚举属性值的数组
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj)); // 输出: [1, 2, 3]
(2)、与 Object.keys() 配合使用
const obj = { x: 10, y: 20 };
const keys = Object.keys(obj); // ["x", "y"]
const values = Object.values(obj); // [10, 20]
(3)、对象扁平化
const data = { p1: { name: "John" }, p2: { name: "Doe" } };
const result = Object.values(data); // [{ name: "John" }, { name: "Doe" }]
3、Object.entries()
(1)、对象自己的所有可枚举属性的键值对数组
const obj = { a: 1, b: 2 };
console.log(Object.entries(obj)); // 输出: [['a', 1], ['b', 2]]
4、Object.fromEntries
(1)、将键值对列表转换为对象的静态方法,与Object.entries()为相反的操作
const obj = [['a', 1], ['b', 2]];
console.log(Object.fromEntries(obj)); // { 'a': 1, 'b': 2}
5、Object.assign()
(1)、合并多个对象(浅拷贝),同名属性会被后续对象的值覆盖
const target = { a: 1 };
const source = { b: 8 };
const source1 = { b: 2 };
Object.assign(target, source, source ); // 输出: { a: 1, b: 2 }
6、Object.defineProperty()
(1)、给一个对象上定义一个新属性,或者修改一个对象的现有属性
const obj = {};
Object.defineProperty(obj, 'name',{
value: '哈哈哈',
writable: true // 允许修改
})
console.log(obj.name) // 哈哈哈
obj.name = '啦啦啦'
console.log(obj.name) // 啦啦啦
//不可被修改
const obj1 = {};
Object.defineProperty(obj1, 'age',{
value: '18',
writable: false // 不允许修改
})
obj1.age= 20
console.log(obj1.age) //18
7、Object.freeze()
(1)、该方法冻结一个对象,防止添加新属性,删除现有属性或修改属性的值
const obj = { name: "hahahaha" };
Object.freeze(obj);
obj.name = "Bob"; // 修改不生效,hahahaha
delete obj.name; // 删除不生效
obj.age = 18; // 无法添加新的属性
8、Object.hasOwn()
(1)、仅检查对象自身属性
const obj = { a: 1 };
console.log(Object.hasOwn(obj, 'a')); // true
console.log(Object.hasOwn(obj, 'b')); // false
9、Object.getOwnPropertyDescriptor
1、用于获取对象的属性
const obj = { name: '张三' };
console.log(Object.getOwnPropertyDescriptor(obj, 'age')); //undefined
console.log(Object.getOwnPropertyDescriptor(obj, 'name')); //{configurable:true, enumerable:true, value: "张三", writable: true}