function getPropByPath(obj, path) { let tempObj = obj; path = path.replace(/\[(\w+)\]/g, ‘.$1‘); path = path.replace(/^\./, ‘‘); let keyArr = path.split(‘.‘); let i = 0; for (let len = keyArr.length; i < len - 1; ++i) { let key = keyArr[i]; if (key in tempObj) { tempObj = tempObj[key]; } else { throw new Error(‘[iView warn]: please transfer a valid prop path to form item!‘); } } return { o: tempObj, k: keyArr[i], v: tempObj[keyArr[i]] }; }
如: var obj = {name:‘objname‘, items:[{value: 0},{value: 1}]}, path = ‘items.0.value‘;
console.log( getPropByPath(obj, path).v );
结果: 0
时间: 2024-10-31 11:14:28