Update dig.md

This commit is contained in:
Angelos Chalaris
2018-07-14 10:25:44 +03:00
committed by GitHub
parent ba65c98d26
commit f76ba78437

View File

@ -1,9 +1,9 @@
### dig ### dig
Return the value in a nested JSON object by the key. Returns the target value in a nested JSON object, based on the given key.
Given the key name (or target), it will loop through each key/value in the object and look for object type. Use the `in` operator to check if `target` exists in `obj`.
If value is an object, dig is called recusively until the first matching key/value is found. If found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found.
``` ```
const dig = (obj, target) => const dig = (obj, target) =>
@ -21,11 +21,10 @@ const dig = (obj, target) =>
const data = { const data = {
level1:{ level1:{
level2:{ level2:{
level3: "some data" level3: 'some data'
} }
} }
}; };
dig(data, 'level3'); // 'some data'
dig(data, 'level3'); // "some data"
dig(data, 'level4'); // undefined dig(data, 'level4'); // undefined
``` ```