Find All Properties - recursive

by jacobwsmith

JavaScript

console.clear();

// Returns the all found values of a property within an object with reference to it's location
// Otherwise returns 'property was not found'
function findAllProperties(name, obj) {
	let keyPath = '';
  const getProperties = (name, obj) => {
    return Object.entries(obj).reduce((accumulator, [key, value]) => {
        keyPath += keyPath === '' ? `${key}` : `.${key}`;
        if (key === name) {
          const rv = [...accumulator, {
            keyPath,
            value
          }];
          keyPath = '';
          return rv;
        }
        if (value && typeof value === 'object' && value.constructor === Object) {
          return [...accumulator, ...getProperties(name, value)];
        }
        return accumulator;
      }, [])
      
  }
  const properties = getProperties(name, obj);
	return properties.length === 0 ? 'property was not found': properties;
}


// Test
{
  const obj = {
    name: 'Susan Sontag',
    bibliography: {
      name: 'bib name',
      prizes: 'National Book Award',
      essays: {
        collections: {
          criticism: [{
            name: 'On Photography',
            subject: 'photography'
          }, {
            name: 'Against Interpretation',
            subject: 'misc.'
          }]
        }
      }
    }
  };

  console.log('foo: ', findAllProperties('foo', obj)); // property was not found
  console.log('name: ', findAllProperties('name', obj)); // Susan Sontag
  console.log('prizes: ', findAllProperties('prizes', obj)); // National Book Award
  console.log('criticism: ', findAllProperties('criticism', obj)); // Array of criticism :)

}