get object values

How to implement a Get object value with paht

Spec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

function getValue (obj, path, defaultValue){
const result = path
.split('.')
.reduce((lastObj, key) => (lastObj ? lastObj[key] : undefined), obj);

if (
defaultValue !== undefined &&
Object.prototype.toString.call(result) !==
Object.prototype.toString.call(defaultValue)
) {
return defaultValue;
}

return result === undefined ? defaultValue : result;

}

getValue(object, path, defaultValue)

Example Usage

1
2
3
4
5
6
7
8
9
10
11
12

import getValue from 'get-object-value';

let demoObject = {
a: {
b: c1
}
};

let v1 = getValue(demoObject, ['a','b']); // return c1

let v1 = getValue(demoObject, ['a','b','d'], 'c2'); // return c2

Set Object Value

Loadash