1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| function getValue(obj, props) { var propsArray = props.split('.'); var currentProp = propsArray[0]; var restProps = propsArray.slice(1); if (obj && obj.hasOwnProperty(currentProp)) { if (restProps.length === 0) { return obj[currentProp]; } else { return getValue(obj[currentProp], restProps.join('.')); } } return undefined; } var obj = { person: { name: "John", age: 30, address: { city: "New York", country: "USA" } } }; var name = getValue(obj, 'person.name'); var age = getValue(obj, 'person.age'); var city = getValue(obj, 'person.address.city'); var country = getValue(obj, 'person.address.country'); var salary = getValue(obj, 'person.salary');
|