From String Of Keys To Hash Value
I have a hash like the one below aa: { categories: { cat1: 'alpha' } } Starting from the string 'aa.categories.cat1', how can I get alpha suing plain JS?
Solution 1:
const result = path.split('.').reduce((a, v) => a[v], object);
Complete snippet:
const object = {
aa: {
categories: {
cat1: 'alpha'
}
}
}
const path = 'aa.categories.cat1';
const result = path.split('.').reduce((a, v) => a[v], object);
console.log(result);
Solution 2:
You can use "Array.split" and "Array.reduce" to achieve this
var obj = {
aa: {
categories: {
cat1: 'alpha'
}
}
}
functiongetValue(d) {
return d.split('.').reduce((o, v) => o[v], obj)
}
console.log(getValue('aa.categories.cat1'))
Post a Comment for "From String Of Keys To Hash Value"