Tag Object Methods: Memahami 20+ Method Built-in JavaScript untuk Manipulasi Data

By | September 27, 2025

Table of Contents

Tag Object Methods: Memahami 20+ Method Built-in JavaScript untuk Manipulasi Data

Pernah nggak sih kamu bingung bedain antara toString(), valueOf(), dan toLocaleString()? Atau bertanya-tanya kapan harus pakai Object.keys() vs Object.values()? Tenang, kamu nggak sendirian! Method built-in JavaScript ini seperti pisau Swiss Armyβ€”setiap tool punya purpose spesifik, dan kalau dipakai dengan tepat, bisa bikin coding-mu jauh lebih efisien.

Bayangin object methods itu seperti toolkit mekanik. Ada kunci inggris untuk general purpose, ada kunci sok yang spesifik, dan ada tool khusus untuk situasi tertentu. Nah, tantangannya adalah tahu tool mana yang dipakai untuk problem apa. Once you master them, you’ll wonder how you ever coded without them!

Di panduan super lengkap ini, kita akan eksplor method-method built-in JavaScript dari yang paling dasar sampai advanced. Aku bakal kasih analogi yang mudah dimengerti, contoh praktis, dan use case nyata. Yuk, tingkatkan skill JavaScript-mu ke level expert!

Kategori Object Methods yang Wajib Dikuasai

Sebelum menyelam, mari kelompokkan method-method ini berdasarkan fungsinya:

Kategori Method Contoh Fungsi Utama
πŸ” Inspection Object.keys(), Object.values() Melihat isi object
πŸ› οΈ Manipulation Object.assign(), Object.defineProperty() Mengubah object
πŸ”’ Protection Object.freeze(), Object.seal() Mengamankan object
πŸ“Š Conversion toString(), valueOf() Mengubah tipe data
πŸ”— Prototype hasOwnProperty(), isPrototypeOf() Working with inheritance

Object Inspection Methods – Mata-mata untuk Object

1. Object.keys() – Ambil Semua Keys

const person = {
    name: 'John',
    age: 30,
    city: 'Jakarta'
};

const keys = Object.keys(person);
console.log(keys); // ['name', 'age', 'city']

Use Case: Looping melalui properties object

// ❌ Cara lama
for (let key in person) {
    if (person.hasOwnProperty(key)) {
        console.log(key, person[key]);
    }
}

// βœ… Cara modern
Object.keys(person).forEach(key => {
    console.log(key, person[key]);
});

2. Object.values() – Ambil Semua Values

const person = { name: 'John', age: 30, city: 'Jakarta' };
const values = Object.values(person);
console.log(values); // ['John', 30, 'Jakarta']

Use Case: Menghitung total values

const sales = { jan: 1000, feb: 1500, mar: 2000 };
const total = Object.values(sales).reduce((sum, value) => sum + value, 0);
console.log(total); // 4500

3. Object.entries() – Ambil Key-Value Pairs

const person = { name: 'John', age: 30, city: 'Jakarta' };
const entries = Object.entries(person);
console.log(entries);
// [['name', 'John'], ['age', 30], ['city', 'Jakarta']]

Use Case: Convert object ke Map

const personMap = new Map(Object.entries(person));
console.log(personMap.get('name')); // John

4. Object.fromEntries() – Kebalikan entries()

const entries = [['name', 'John'], ['age', 30], ['city', 'Jakarta']];
const person = Object.fromEntries(entries);
console.log(person); // { name: 'John', age: 30, city: 'Jakarta' }

Use Case: Transform array of pairs jadi object

Object Manipulation Methods – Edit Object dengan Aman

5. Object.assign() – Merge Objects

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const result = Object.assign(target, source);
console.log(result); // { a: 1, b: 4, c: 5 }
console.log(target); // { a: 1, b: 4, c: 5 } - target ikut berubah!

Best Practice: Gunakan empty object sebagai target

const safeMerge = Object.assign({}, target, source);
// target tidak berubah

6. Spread Operator vs Object.assign()

// ❌ Object.assign() yang mutable
const merged1 = Object.assign(target, source); // target berubah

// βœ… Spread operator (immutable)
const merged2 = { ...target, ...source }; // target tidak berubah

// βœ… Object.assign() yang immutable
const merged3 = Object.assign({}, target, source); // target tidak berubah

7. Object.defineProperty() – Custom Property Behavior

const obj = {};

Object.defineProperty(obj, 'readOnlyProp', {
    value: 42,
    writable: false,       // Tidak bisa diubah
    enumerable: true,      // Muncul di Object.keys()
    configurable: false    // Tidak bisa dihapus
});

obj.readOnlyProp = 100; // Error di strict mode
console.log(obj.readOnlyProp); // 42 (tetap)

Use Case: Computed properties

const person = {
    firstName: 'John',
    lastName: 'Doe'
};

Object.defineProperty(person, 'fullName', {
    get() {
        return `${this.firstName} ${this.lastName}`;
    },
    set(value) {
        const parts = value.split(' ');
        this.firstName = parts[0];
        this.lastName = parts[1] || '';
    },
    enumerable: true
});

console.log(person.fullName); // John Doe
person.fullName = 'Jane Smith';
console.log(person.firstName); // Jane

Object Protection Methods – Kunci Object dari Perubahan

8. Object.freeze() – Bekukan Object

const frozenObj = {
    name: 'John',
    address: {
        city: 'Jakarta',
        zip: '12345'
    }
};

Object.freeze(frozenObj);

frozenObj.name = 'Jane'; // ❌ Tidak berubah (strict mode error)
frozenObj.age = 30;      // ❌ Tidak bisa tambah property

// TAPI inner object masih bisa diubah!
frozenObj.address.city = 'Bandung'; // βœ… Masih bisa
console.log(frozenObj.address.city); // Bandung

9. Object.seal() – Segel Object

const sealedObj = { name: 'John', age: 30 };
Object.seal(sealedObj);

sealedObj.name = 'Jane';     // βœ… Bisa diubah
sealedObj.city = 'Jakarta';  // ❌ Tidak bisa tambah property
delete sealedObj.age;        // ❌ Tidak bisa hapus property

console.log(sealedObj); // { name: 'Jane', age: 30 }

10. Object.preventExtensions() – Cegah Penambahan

const obj = { name: 'John' };
Object.preventExtensions(obj);

obj.name = 'Jane';     // βœ… Bisa diubah
obj.age = 30;         // ❌ Tidak bisa tambah property
delete obj.name;       // βœ… Bisa hapus property

console.log(obj); // {}

Comparison Table: Protection Methods

Method Edit Values Add Properties Delete Properties
Object.freeze() ❌ ❌ ❌
Object.seal() βœ… ❌ ❌
preventExtensions() βœ… ❌ βœ…

Conversion Methods – Ubah Object ke Tipe Lain

11. toString() – Representasi String

const obj = { name: 'John', age: 30 };
console.log(obj.toString()); // [object Object]

// Custom toString()
const person = {
    name: 'John',
    age: 30,
    toString() {
        return `${this.name} (${this.age} years old)`;
    }
};

console.log(person.toString()); // John (30 years old)
console.log('Info: ' + person); // Info: John (30 years old)

12. valueOf() – Nilai Primitive

const obj = { value: 42 };
console.log(obj.valueOf()); // { value: 42 } (default)

const customObj = {
    value: 100,
    valueOf() {
        return this.value;
    }
};

console.log(customObj + 50); // 150 (otomatis panggil valueOf())
console.log(customObj > 99); // true

13. toLocaleString() – Format Lokal

const date = new Date();
console.log(date.toString());      // Mon Dec 04 2023 10:30:00 GMT+0700
console.log(date.toLocaleString());// 04/12/2023, 10:30:00

const number = 123456.789;
console.log(number.toLocaleString('id-ID')); // 123.456,789
console.log(number.toLocaleString('en-US')); // 123,456.789

Prototype dan Inheritance Methods

14. hasOwnProperty() – Cek Property Milik Sendiri

const obj = { name: 'John' };

console.log(obj.hasOwnProperty('name'));    // true
console.log(obj.hasOwnProperty('toString'));// false (dari prototype)
console.log(obj.hasOwnProperty('age'));     // false

Use Case: Safe property checking

// ❌ Bermasalah jika object punya property 'hasOwnProperty'
const trickyObj = { hasOwnProperty: 'I am a string' };
// trickyObj.hasOwnProperty('name'); // Error!

// βœ… Safe way
Object.prototype.hasOwnProperty.call(trickyObj, 'name');
// atau
Object.hasOwn(trickyObj, 'name'); // ES2022

15. isPrototypeOf() – Cek Relationship Prototype

function Animal(name) {
    this.name = name;
}

function Dog(name, breed) {
    Animal.call(this, name);
    this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype);

const myDog = new Dog('Buddy', 'Golden');

console.log(Animal.prototype.isPrototypeOf(myDog)); // true
console.log(Dog.prototype.isPrototypeOf(myDog));    // true
console.log(Object.prototype.isPrototypeOf(myDog)); // true

16. propertyIsEnumerable() – Cek Enumerability

const obj = {
    name: 'John',
    age: 30
};

// Tambah non-enumerable property
Object.defineProperty(obj, 'secret', {
    value: 'hidden',
    enumerable: false
});

console.log(obj.propertyIsEnumerable('name'));  // true
console.log(obj.propertyIsEnumerable('secret')); // false
console.log(obj.propertyIsEnumerable('toString')); // false

ES6+ Modern Object Methods

17. Object.is() – Comparison yang Lebih Akurat

console.log(Object.is(0, -0));     // false
console.log(0 === -0);            // true

console.log(Object.is(NaN, NaN)); // true
console.log(NaN === NaN);         // false

console.log(Object.is('hello', 'hello')); // true

18. Object.hasOwn() – Modern hasOwnProperty()

const obj = { name: 'John' };

// βœ… Recommended (ES2022)
console.log(Object.hasOwn(obj, 'name'));    // true
console.log(Object.hasOwn(obj, 'toString'));// false

// ❌ Masalah dengan method shadowing
const trickyObj = { hasOwnProperty: 'I am a string' };
console.log(Object.hasOwn(trickyObj, 'name')); // Aman!

19. Object.getOwnPropertyDescriptors()

const obj = {
    name: 'John',
    get upperName() {
        return this.name.toUpperCase();
    }
};

const descriptors = Object.getOwnPropertyDescriptors(obj);
console.log(descriptors.name);
// { value: 'John', writable: true, enumerable: true, configurable: true }

console.log(descriptors.upperName);
// { get: [Function: get upperName], set: undefined, enumerable: true, configurable: true }

Practical Use Cases dan Patterns

20. Deep Clone Object

function deepClone(obj) {
    if (obj === null || typeof obj !== 'object') return obj;
    if (obj instanceof Date) return new Date(obj);
    if (obj instanceof Array) return obj.map(item => deepClone(item));
    
    const descriptors = Object.getOwnPropertyDescriptors(obj);
    const clone = Object.create(Object.getPrototypeOf(obj), descriptors);
    
    Object.getOwnPropertySymbols(obj).forEach(sym => {
        clone[sym] = deepClone(obj[sym]);
    });
    
    return clone;
}

const original = { 
    name: 'John', 
    address: { city: 'Jakarta' },
    [Symbol('id')]: 123 
};
const cloned = deepClone(original);

21. Object Transformation Pipeline

const users = [
    { id: 1, name: 'John', age: 30, active: true },
    { id: 2, name: 'Jane', age: 25, active: false },
    { id: 3, name: 'Bob', age: 35, active: true }
];

// Pipeline transformation
const result = users
    .filter(user => user.active)
    .map(user => Object.fromEntries(
        Object.entries(user)
            .filter(([key]) => key !== 'active')
            .map(([key, value]) => [key, key === 'name' ? value.toUpperCase() : value])
    ))
    .reduce((acc, user) => {
        acc[user.id] = user;
        return acc;
    }, {});

console.log(result);
// { 
//   1: { id: 1, name: 'JOHN', age: 30 },
//   3: { id: 3, name: 'BOB', age: 35 }
// }

22. Configurable Object Builder

function createConfig(config) {
    const defaults = {
        theme: 'light',
        language: 'en',
        notifications: true,
        version: '1.0.0'
    };
    
    const finalConfig = Object.assign({}, defaults, config);
    
    // Freeze untuk production
    if (process.env.NODE_ENV === 'production') {
        Object.freeze(finalConfig);
    }
    
    return finalConfig;
}

const myConfig = createConfig({
    theme: 'dark',
    language: 'id'
});

Performance Considerations

Methods yang Efficient

// βœ… Efficient untuk large objects
Object.keys(obj).length; // Cek jika object kosong

// ❌ Kurang efficient
JSON.stringify(obj) === '{}'; // Lebih lambat

Memory Optimization

// βœ… Gunakan same prototype untuk banyak objects
function createUser(name) {
    const user = Object.create(userMethods);
    user.name = name;
    return user;
}

const userMethods = {
    getName() { return this.name; },
    setName(name) { this.name = name; }
};

Common Mistakes dan Best Practices

Mistake 1: Modifying Built-in Prototypes

// ❌ JANGAN lakukan ini!
Object.prototype.log = function() {
    console.log(this);
};

// βœ… Gunakan utility function instead
function logObject(obj) {
    console.log(obj);
}

Mistake 2: Ignoring Property Descriptors

const obj = { name: 'John' };

// ❌ Asumsi semua property writable
obj.name = 'Jane'; // Bisa error jika property read-only

// βœ… Cek descriptor dulu
const descriptor = Object.getOwnPropertyDescriptor(obj, 'name');
if (descriptor.writable) {
    obj.name = 'Jane';
}

Browser Compatibility dan Polyfills

Modern Methods Compatibility

// Polyfill untuk Object.entries() (jika needed)
if (!Object.entries) {
    Object.entries = function(obj) {
        const ownProps = Object.keys(obj);
        let i = ownProps.length;
        const resArray = new Array(i);
        
        while (i--) {
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        }
        
        return resArray;
    };
}

Kesimpulan: Master Object Methods untuk JavaScript yang Lebih Powerful

Dengan menguasai object methods, kamu bisa menulis code yang lebih clean, efficient, dan maintainable. Yang sudah kita pelajari:

  • βœ… Inspection methods untuk exploring objects
  • βœ… Manipulation methods untuk modifying objects
  • βœ… Protection methods untuk securing objects
  • βœ… Conversion methods untuk type transformations
  • βœ… Prototype methods untuk inheritance workflows
  • βœ… Modern ES6+ methods untuk contemporary coding

Ingat, practice makes perfect. Coba implementasikan methods ini dalam project sehari-hari, dan perhatikan bagaimana code-mu menjadi lebih expressive dan powerful.

Sekarang waktunya action! Pick 5 methods dari artikel ini yang belum pernah kamu gunakan, dan coba implementasikan dalam code-mu. Happy coding! πŸš€

“Mastering JavaScript object methods is like having a superpower – suddenly, complex data manipulations become simple and elegant.” – JavaScript Developer