Skip to content

Instantly share code, notes, and snippets.

@tranphuquy19
Created August 14, 2023 15:18
Show Gist options
  • Save tranphuquy19/2b11242f03a8fd09b524bba570f518ff to your computer and use it in GitHub Desktop.
Save tranphuquy19/2b11242f03a8fd09b524bba570f518ff to your computer and use it in GitHub Desktop.
Search value in a json object
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