Skip to content

Instantly share code, notes, and snippets.

@aminsol
Created January 18, 2021 08:29
Show Gist options
  • Save aminsol/28f79fa3b35335857239919f699b9212 to your computer and use it in GitHub Desktop.
Save aminsol/28f79fa3b35335857239919f699b9212 to your computer and use it in GitHub Desktop.
Inserting a value into an object with a path string and the second file is about finding a value in an object with a path
function createObjectFromPath (root, path, value) {
const segments = path.split('.')
let cursor = root
let segment
for (let i = 0; i < segments.length; i++) {
segment = segments[i]
if (segment === '[]') {
continue
}
let newObj = cursor[segment] || {}
if (i + 1 < segments.length && segments[i + 1] === '[]') {
if (!cursor[segment] || !Array.isArray(cursor[segment])) {
newObj = [{}]
cursor = cursor[segment] = newObj
cursor = newObj[0]
} else {
newObj = {}
cursor[segment].push(newObj)
cursor = newObj
}
}
else {
if (i === segments.length - 1) {
cursor = cursor[segment] = value
} else {
cursor = cursor[segment] = newObj
}
}
}
}
const r = {}
createObjectFromPath(r, 'a.[].b.c', 5)
console.log(r)
createObjectFromPath(r, 'a.[].b.c', 6)
console.log(r)
createObjectFromPath(r, 'a.[].b.d', 7)
console.log(r)
function findFieldsByPath (subjectObject, path, successCallback = undefined) {
let current = subjectObject
const fields = path.split('.')
if (fields.includes('')) {
console.error(`[findFieldsByPath] Invalid path ${path}`)
}
const result = {
path: path,
parents: [],
fieldValues: [],
fieldName: '',
isSuccess: false
}
for (let i = 0; i < fields.length; i++) {
const subField = fields[i]
if (i === fields.length - 1 && current !== undefined) {
result.parents = [current]
result.fieldValues = [current[subField]]
result.fieldName = subField
result.isSuccess = true
break
} else {
if (current && typeof current !== 'string') {
if (subField in current) {
current = current[subField]
} else if (subField === '[]' && Array.isArray(current)) {
const addSubResults = ({ parents, fieldName, fieldValues }) => {
result.parents = result.parents.concat(parents)
result.fieldName = fieldName
result.fieldValues = result.fieldValues.concat(fieldValues)
result.isSuccess = true
}
for (let k = 0; k < current.length; k++) {
findFieldsByPath(current[k], fields.slice(i + 1).join('.'), addSubResults)
}
break
}
} else {
current = undefined
}
}
}
if (result.isSuccess) {
if (typeof successCallback === 'function') {
successCallback(result)
} else {
return result
}
}
}
subject = {
a: {
b: {
people: [{ name: 'Amin', last: 'Soltani' }, { name: 'Darya', last: 'who?' }]
}
},
c: {
name: 'WRONG'
}
}
path = 'a.b.people.[].name'
console.log(findFieldsByPath(subject, path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment