Assume I have an object:
var abc = {
a: 'a',
b: 'b',
c: {
x: 'c',
y: 'd'
}
}
Now I want to fetch object values based on values present in an array below dynamically
var arr = ['a', 'b', 'c.x']
Assume I have an object:
var abc = {
a: 'a',
b: 'b',
c: {
x: 'c',
y: 'd'
}
}
Now I want to fetch object values based on values present in an array below dynamically
var arr = ['a', 'b', 'c.x']
NOTE: the following solution would work with the given scenario, where object properties are indicated using the dot notation, but will fail if you use bracket notation (e.g. c[x]
).
const abc = {
a: 'aVal',
b: 'bVal',
c: {
x: 'cxVal',
y: 'cyVal'
},
d: {
x: 'dxVal',
y: {
z: 'dyzVal',
w: 'dywVal'
}
}
};
const arr = ['a', 'b', 'c.x', 'd.y.w'];
function getValues(obj, keysArr) {
return keysArr.map(key => {
return key.split('.').reduce((acc, item) => {
return acc[item];
}, obj);
});
}
const values = getValues(abc, arr);
console.log(values);
You can create an extension like this:
Object.defineProperty(Object.prototype, 'valueAt', {
value: function (location, defaultValue) {
const routes = location.split('.');
const lastRoute = routes.pop();
let value = routes.reduce(
(current, route) => current && current[route],
this
);
if (value) return value[lastRoute] || defaultValue;
else return defaultValue;
},
writable: true,
configurable: true,
enumerable: false,
});
and then use:
abc.valueAt("c.x");
You could split the strings for getting an array and reduce the keys by accessing the object.
var getValue = (object, keys) => keys.reduce((o, k) => (o || {})[k], object),
object = { a: 'a', b: 'b', c: { x: 'c', y: 'd' } },
keys = ['a', 'b', 'c.x'],
result = keys.map(s => getValue(object, s.split('.')));
console.log(result);