Object 物件
Node.js Object 物件
Categories:
物件函式
变数 | 说明 |
---|---|
Object.keys() | 物件所有键值 |
Object.values() | 物件所有数值 |
Object.entries() | 把物件转为阵列 |
Object.fromEntries() | 把阵列转为物件 |
Object.assign() | 複製物件 |
Object.hasOwnProperty() | 是否是物件本身的属性 |
Object.gerOwnPropertyDescriptors() | 得到这个物件内容值的一些属性 |
Object.setPrototypeOf() | 设定物件原型 |
Object.getPrototypeOf() | 取的物件原型 |
Object.entries 把物件转为阵列
const Employee = {
name: 'KJ',
age: 17
}
// [ [ 'name', 'KJ' ], [ 'age', 17 ] ]
console.log(Object.entries(Employee))
Object.gerOwnPropertyDescriptors 得到这个物件内容值的一些属性
const Employee = {
name: 'KJ',
age: 17,
sayHi : () => {
console.log(`Hi`)
}
}
// {
// name: { value: 'KJ', writable: true, enumerable: true, configurable: true },
// age: { value: 17, writable: true, enumerable: true, configurable: true },
// sayHi: {
// value: [Function: sayHi],
// writable: true,
// enumerable: true,
// configurable: true
// }
// }
console.log(Object.getOwnPropertyDescriptors(Employee));
assign 複製物件
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
使用 Object.assign 複製物件
const Employee = {
name: 'KJ',
age: 17,
sayHi : () => {
console.log(`Hi`)
}
};
// 使用 Object.assign 複製物件
NewEmployee = Object.assign({}, Employee);
NewEmployee.name = 'Kay';
NewEmployee.age = 19;
// { name: 'KJ', age: 17, sayHi: [Function: sayHi] }
console.log(Employee);
// { name: 'Kay', age: 19, sayHi: [Function: sayHi] }
console.log(NewEmployee);
使用运算元 ...
合併物件
let person = {
name: 'KJ',
age: 17,
};
let job = {
jobTitle: 'Software Engineer',
location: 'Taiwan'
};
let employee = {
...person,
...job
};
console.log(employee);
// {
// name: 'KJ',
// age: 17,
// jobTitle: 'Software Engineer',
// location: 'Taiwan'
// }
后来的物件资料会复盖前面的物件资料
let person = {
name: 'KJ',
age: 17,
jobTitle: 'No Job',
};
let job = {
jobTitle: 'Software Engineer',
location: 'Taiwan'
};
let employee = {
...person,
...job
};
console.log(employee);
// {
// name: 'KJ',
// age: 17,
// jobTitle: 'Software Engineer',
// location: 'Taiwan'
// }
参考资料
- Object - JavaScript | MDN
- JS 深拷贝与浅拷贝 | Explosion Units
- [How to Merge Objects in JavaScript](How to Merge Objects in JavaScript)