Skip to content

Instantly share code, notes, and snippets.

@intoxopox
Last active May 11, 2021 22:31
Show Gist options
  • Save intoxopox/dd414fa415b2ad1734c76e6a735f0ac2 to your computer and use it in GitHub Desktop.
Save intoxopox/dd414fa415b2ad1734c76e6a735f0ac2 to your computer and use it in GitHub Desktop.
ObjectUtil - Handy Object functions
////////////////////////////////////////////////////////////////////////////////
// Copyright(C) 2018 David Hamiter
////////////////////////////////////////////////////////////////////////////////
'use strict';
/**
* @author David Hamiter
* Static class for advanced Object manipulation, searching, comparison, etc.
*/
abstract class ObjectUtil {
//----------------------------------------------------------------------
//
// Properties
//
//----------------------------------------------------------------------
//----------------------------------------------------------------------
//
// Constructor
//
//----------------------------------------------------------------------
private constructor() { } // Static class cannot be instantiated
//----------------------------------------------------------------------
//
// Methods
//
//----------------------------------------------------------------------
/**
* Finds the given sub-object in the provided object based on key.
* This will always return the 1st match or undefined
* @param obj The object to search
* @param key The key to search for
* @returns The 1st matching object with the provided key or undefined
*/
static findByKey(obj: any, key: string): any {
//Early return
if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') {
return obj[key];
}
var result: any;
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop] === 'object') {
result = ObjectUtil.findByKey(obj[prop], key);
if (result) break;
}
}
return result;
}
/**
* Finds the given sub-object in the provided object based on the provide propName and value.
* This will always return the 1st match or undefined
* @param obj The object to search
* @param propName The name of the property (or key) to search for
* @param value The value the given propName must have for a valid match to be found
* @returns The 1st matching object with the provided key or undefined
*/
static findByPropValue(obj:any, propName:string, value:any): any {
//Early return
if (obj[propName] === value) {
return obj;
}
var result: any;
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop] === 'object') {
result = ObjectUtil.findByPropValue(obj[prop], propName, value);
if (result) break;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment