Created
August 14, 2023 15:18
-
-
Save tranphuquy19/2b11242f03a8fd09b524bba570f518ff to your computer and use it in GitHub Desktop.
Search value in a json object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function search(obj, value, checkedObjs = [], path = '') { | |
if (Array.isArray(obj)) { | |
for (var i = 0; i < obj.length; i++) { | |
if (obj[i] === value || (typeof obj[i] === 'string' && obj[i].includes(value))) { | |
return path + '[' + i + ']'; | |
} | |
} | |
} else if (typeof obj === 'function') { | |
var str = obj.toString(); | |
if (str.includes(value)) { | |
return path; | |
} | |
} else if (typeof obj === 'object') { | |
if (checkedObjs.includes(obj)) { | |
return false; // Đối tượng đã được kiểm tra | |
} | |
checkedObjs.push(obj); | |
for (var key in obj) { | |
var newPath = path === '' ? key : path + '.' + key; | |
if (typeof obj[key] === 'object' || typeof obj[key] === 'function') { | |
var result = search(obj[key], value, checkedObjs, newPath); | |
if (result !== false) { | |
return result; | |
} | |
} else if (obj[key] === value || (typeof obj[key] === 'string' && obj[key].includes(value))) { | |
return newPath; | |
} | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment