@innostes/object-helper
Version:
A utility library to help with object & array manipulations like sorting, filtering, and removing duplicates.
68 lines (67 loc) • 2.47 kB
JavaScript
;
// Copyright (c) 2025 Innostes Solutions.
// All rights reserved.
Object.defineProperty(exports, "__esModule", { value: true });
exports.deepClone = deepClone;
exports.mergeObjects = mergeObjects;
exports.pickElements = pickElements;
exports.removeProperties = removeProperties;
// Licensed under the MIT License. You may obtain a copy of the License at
// https://opensource.org/licenses/MIT
// This file is a part of the "array-helper" library, built by Innostes Solutions.
// For more information, visit: https://github.com/innostes/array-helper
// ================================
// ** Description: Utility functions for object manipulation **
// ================================
/**
* Deep clones an object.
* This method serializes the object to JSON and parses it back to create a new instance.
* **Note**: It does not handle circular references or special object types like `Date`.
* @param obj The object to deep clone.
* @returns A new object that is a deep clone of the input.
*/
function deepClone(obj) {
try {
return JSON.parse(JSON.stringify(obj));
}
catch (error) {
throw new Error("Failed to deep clone object. Please ensure it is serializable.");
}
}
/**
* Merges two objects. Properties from the source object will override properties in the target object.
* @param target The target object.
* @param source The source object whose properties will override those in the target.
* @returns A new object that merges the target and source.
*/
function mergeObjects(target, source) {
return Object.assign(Object.assign({}, target), source);
}
/**
* Picks specific properties from an object based on a list of keys.
* @param obj The object from which to pick the properties.
* @param keys The keys to pick from the object.
* @returns A new object containing only the specified properties.
*/
function pickElements(obj, keys) {
const result = {};
keys.forEach((key) => {
if (key in obj) {
result[key] = obj[key];
}
});
return result;
}
/**
* Removes specific properties from an object based on a list of keys.
* @param obj The object from which to remove properties.
* @param keys The keys to remove from the object.
* @returns A new object without the specified properties.
*/
function removeProperties(obj, keys) {
const result = Object.assign({}, obj);
keys.forEach((key) => {
delete result[key];
});
return result;
}