Object 物件

Node.js Object 物件

物件函式

變數 說明
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'
// }

取得物件指定鍵值並宣告為變數

let person = {
  name: 'KJ',
  age: 17,
  jobTitle: 'No Job',
};

// KJ, 17
const { name, age } = person;

取得物件指定鍵值並重新命名宣告的變數

let person = {
  name: 'KJ',
  age: 17,
  jobTitle: 'No Job',
};

// KJ, 17
const { 
    name: kj_name, 
    age: kj_age 
} = person;

參考資料