---
# System prepended metadata

title: JavaScript 常用物件方法
tags: [JavaScript]

---

###### tags: `JavaScript`

# JavaScript 常用物件方法

## 物件讀取方式
```javascript=
let home = {
    dogs: 10,
    people: 5,
    '789': 3
}

console.log(home.dogs) // 10
// console.log(home.789) // 會出錯
// 如果物件裡面的屬性是數字的時候就需要用這種方式來讀取
console.log(home['789']) // 3
```
---

## 物件新增方式
```javascript=
let home = {
    dogs: 10,
    people: 5,
}
home.cat = 10
console.log(home) // {dogs: 10, people: 5, cat: 10}
```
---

## delete 刪除物件資料

```javascript=
let home = {
    dogs: 10,
    people: 5,
    cat: 3
}
delete home.cat
console.log(home) // {dogs: 10, people: 5}

```
---


# Object 使用 forEach()

## Object.keys()

```javascript=
const obj = {
  name: 'Jean-Luc Picard',
  rank: 'Captain'
};

console.log(Object.keys(obj));
// ['name', 'rank']

Object.keys(obj).forEach(key => {
  console.log(key, obj[key]);
  // name Jean-Luc Picard
  // rank Captain
});
```

## Object.values()

```javascript=
const obj = {
  name: 'Jean-Luc Picard',
  rank: 'Captain'
};

console.log(Object.values(obj));
// ['Jean-Luc Picard', 'Captain']

Object.values(obj).forEach(val => {
  console.log(val);
  // Jean-Luc Picard
  // Captain
});
```

## Object.entries()

```javascript=
const obj = {
  name: 'Jean-Luc Picard',
  rank: 'Captain'
};

console.log(Object.entries(obj));
// [
//   ["name", "Jean-Luc Picard"],
//   ["rank", "Captain"]
// ]

Object.entries(obj).forEach(entry => {
  const [key, value] = entry;
  console.log(key, value);
  // name Jean-Luc Picard
  // rank Captain
});
```