|
| 1 | +//OBJECTS METHODS |
| 2 | + |
| 3 | +//1. Object.keys(abj) -Returns an array of objects keys(property names) |
| 4 | + |
| 5 | +const user = { |
| 6 | + id: 1, |
| 7 | + name: "David", |
| 8 | + age: 40 |
| 9 | +} |
| 10 | +console.log(Object.keys(user))//[ 'id', 'name', 'age' ] |
| 11 | + |
| 12 | +//2. Object.values(abj)-Returns an array of an object values |
| 13 | + |
| 14 | +const user2 = { |
| 15 | + id: 2, |
| 16 | + name: "Robert", |
| 17 | + age: 50 |
| 18 | +} |
| 19 | +console.log(Object.values(user2))//[ 2, 'Robert', 50 ] |
| 20 | + |
| 21 | +//3.Object.entries(obj)-Returns an array of key-value pairs |
| 22 | + |
| 23 | +const user3 = { |
| 24 | + id: 3, |
| 25 | + name: "Kim", |
| 26 | + age: 20 |
| 27 | +} |
| 28 | +console.log(Object.entries(user3))//[ [ 'id', 3 ], [ 'name', 'Kim' ], [ 'age', 20 ] ] |
| 29 | + |
| 30 | +//4. Object.freeze(obj) -Prevents modification of an object |
| 31 | + |
| 32 | +const user4 = { |
| 33 | + id: 1, |
| 34 | + name: "Ann", |
| 35 | + age: 25 |
| 36 | +} |
| 37 | + |
| 38 | +Object.freeze(user4) |
| 39 | +user4.name = "Sarah"//wont change the object value |
| 40 | +user4.age = 35//won't change object value |
| 41 | +console.log(user4)//{ id: 1, name: 'Ann', age: 25 } |
| 42 | + |
| 43 | + |
| 44 | +//5.Object.seal()-Prevents adding/removing properties, but you can still update existing values. |
| 45 | + |
| 46 | +const user5 = { |
| 47 | + name: "Alice", |
| 48 | + age: 25 |
| 49 | +}; |
| 50 | + |
| 51 | +Object.seal(user); |
| 52 | + |
| 53 | +user.age = 30; // works |
| 54 | +user.city = "Nairobi"; // wont add |
| 55 | + |
| 56 | +console.log(user); // { name: "Alice", age: 30 } |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | +//6.Object.assign()-Copies values from one object to another. |
| 62 | + |
| 63 | +const user6 = { |
| 64 | + name: "Alice" |
| 65 | +}; |
| 66 | +const details = { |
| 67 | + age: 25, |
| 68 | + city: "Nairobi" |
| 69 | +}; |
| 70 | + |
| 71 | +const merged = Object.assign({}, user, details); |
| 72 | + |
| 73 | +console.log(merged);// { name: "Alice", age: 25, city: "Nairobi" } |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | +//7. Object.hasOwn() (or hasOwnProperty) -Checks if an object has a specific property. |
| 78 | + |
| 79 | +const user7 = { name: "Alice", age: 25 }; |
| 80 | + |
| 81 | +console.log(Object.hasOwn(user7, "name")); // true |
| 82 | +console.log(Object.hasOwn(user7, "city")); // false |
| 83 | + |
| 84 | + |
0 commit comments