1. 程式人生 > >輸入任意物件,任意引數路徑能獲取對應的值的 js 函式

輸入任意物件,任意引數路徑能獲取對應的值的 js 函式

var obj = { 
		selector: {
			to: { toutiao: "FE Coder"} 
		}, 
		target: [
			1, 
			2, 
			{ name: 'byted' }
		]
	};
 function get(data, ...args) {
    const res = JSON.stringify(data);
    var a = args.map((item) => (new Function(`return ${res}.${item} `))());
    // var a = args.map((item) => (eval(`(function(){ return ${res}.${item} })`))());
    console.log(a)
}
get(obj, 'selector.to.toutiao', 'target[0]', 'target[2].name');