const obj = {
selector: {
to: { toutiao: "FE Coder"}
},
target: [1, 2, { name: 'byted'}]
};
get(obj, 'selector.to.toutiao', 'target[0]', 'target[2].name');
// [ 'FE Coder', 1, 'byted']
function get(data, ...args) {
return args.map((item) => {
const paths = item.split('.');
let res = data;
paths.map(path => res = res[path]);
return res;
})
}
"target[2].name".split(/\[|\]|\./)
// => ["target", "2", "", "name"]
["target", "2", "", "name"].reduce((p, c) => {
if (typeof p === 'undefined' || c === "") return p
return p[c]
}, obj)
// => 'byted'
function get(obj, ...args) {
return args.map(item => {
return item.split(/\.|\[|\]/)
.reduce((p, c) => {
if (typeof p === 'undefined' || c === "") return p
return p[c]
}, obj)
})
}
const obj = { selector: { to: { toutiao: "FE Coder"} }, target: [1, 2, { name: 'byted'}]};
console.log(get(obj, 'selector.to.toutiao', 'target[0]', 'target[2].name'));
// => [ 'FE Coder', 1, 'byted']