Skip to content

Instantly share code, notes, and snippets.

@keybraker
Created February 1, 2021 11:12
Show Gist options
  • Save keybraker/209fa6e922f6546bca555d44bbf906de to your computer and use it in GitHub Desktop.
Save keybraker/209fa6e922f6546bca555d44bbf906de to your computer and use it in GitHub Desktop.
A simple function that lets you access complex object properties with the use of a single string Raw
const countries = [
{
country: {
name: 'Greece',
id: 1,
people: [
[1, 2, 3],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
[
['alice'],
['john'],
{
test: [
['deep']
]
}
]
]
}
}
];
const publishers = {
languages: [
'greek',
'english',
{ dialect: ['one', 'two'] }
]
};
console.log('Access array without name: ', propertyByString(countries, '$0.country.name'));
// "Access array without name: ", "Greece"
console.log('Access array of object: ', propertyByString(publishers, 'languages$0'));
// "Access array of object: ", "greek"
console.log('Access object inside of array: ', propertyByString(publishers, 'languages$2.dialect$1'));
// "Access array of object: ", "greek"
console.log('Access 2d-array inside of array of object: ', propertyByString(countries, '$0.country.people$1$11'));
// "Access 2d-array inside of array of object: ", 11
console.log('An extreme example: ', propertyByString(countries, '$0.country.people$2$2.test$0$0'));
// "An extreme example: ", "deep"
console.log('If something is wrong null is returned: ', propertyByString(countries, '$a.name'));
// "If something is wrong null is returned: ", null
console.log('If something is wrong null is returned: ', propertyByString(countries, '$0.name'));
// "If something is wrong null is returned: ", null
function propertyByString(obj: any, path: string): any | null {
if (!obj || !path) return null;
const properties = path.split('.');
let prop: any = obj;
for (let i = 0; i < properties.length; i++) {
const array_prop = propByArray(prop, properties[i]);
if (!array_prop) {
prop = prop[properties[i]];
if (!prop)
return null;
} else {
prop = array_prop;
}
}
return prop;
}
function propByArray(obj: any, path: string): any | null {
const array_property = path.split('$');
if (array_property.length === 0)
return null;
if (array_property[0] !== '')
obj = obj[array_property[0]];
if (!obj)
return null;
let array_property_number = []
for (let i = 1; i < array_property.length; i++) {
const index_cancdidate = +array_property[i];
if (typeof index_cancdidate === "number")
array_property_number.push(index_cancdidate);
else
return null;
}
for (let i = 0; i < array_property_number.length; i++) {
obj = obj[array_property_number[i]];
if (!obj)
return null;
}
return obj;
}
@dkarnikis
Copy link

Nice job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment