You can use Proxy:
const obj = new Proxy({
data: {
users: {
admins: {
dashboard: [10, 21, 31, 41],
}
}
},
}, {
get: function (map, key, receiver) {
try {
return eval(`map.${key}`)
} catch (error) {
return undefined;
};
},
});
obj['data.users.admins.dashboard[3]'] // 41
obj['erter.sdfdsfds.admins.sdfsdf[3]'] // undefined
In normal objects it would throw an error can't read property of undefined == better than regular objects in js :)
Updated:
https://repl.it/repls/HarmlessMessyCommas
const obj = new Proxy({
data: {
users: {
admins: {
dashboard: [10, 21, 31, 41, {
hi: 'I am hi'
}],
}
}
},
}, {
get: function (map, key, receiver) {
try {
let splitedKey = key.split(".");
let current = map;
while (splitedKey.length > 0) {
let newValue = splitedKey.shift();
let openingBracketIndex = newValue.lastIndexOf("[");
let arrIndex = Number(newValue.slice(openingBracketIndex + 1, newValue.length - 1));
let isArr = !isNaN(arrIndex)
if (openingBracketIndex > -1 && newValue[newValue.length - 1] === "]" && isArr) {
let arrName = newValue.slice(0, openingBracketIndex);
current = current[arrName][arrIndex];
} else {
current = current[newValue];
}
}
return current;
} catch (error) {
return undefined;
};
},
});
console.log(obj['data.users.admins.dashboard[3]'] == 41);
console.log(obj['data.users.admins.dashboard[0]'] == 10);
console.log(obj["data.users.admins.dashboard[4].hi"] === "I am hi");
console.log(obj['erter.sdfdsfds.admins.sdfsdf[3]'] === undefined)
It works but not perfectly, especially with nested arrays are not going to work b/c even a human wouldn't know if someone is trying to access a property name or array, ex:
const map = {
"dashboard[1]": 'i am string',
"dashboard": [1, 2],
}
So if someone wrote map.dashboard[1] so it is going to return "2" instead of "i am string" b/c if condition for array is above the else condition (else condition = if not array)
I hope it helps :)
obj[data.users.admins.dashboard[3]](without the quotes) not do what you intend?