Skip to content

Instantly share code, notes, and snippets.

@shivanshtalwar0
Last active April 3, 2024 13:54
Show Gist options
  • Save shivanshtalwar0/0a6bae840ff0fad3accf41048248d8b3 to your computer and use it in GitHub Desktop.
Save shivanshtalwar0/0a6bae840ff0fad3accf41048248d8b3 to your computer and use it in GitHub Desktop.
this gist gives working example of converting path to object for example it converts string 'band.material.quality' and value to ```js {band:{material:{quality:value}}}```
const object = {
"customer.firstname": "raj",
"customer.lastname": "sharma",
"kop.shak.rap": 99,
"kop.shak.saip": 99,
simon: "regular",
};
function convertPathObjectToObject(object: any) {
function injectInChild(arr: any, val: any, obj: any = {}, k: any = 0) {
if (_.size(arr) - 1 == k) {
obj[arr[k]] = val
return obj
}
if (_.isNil(obj[arr[k]])) {
obj[arr[k]] = {}
}
return injectInChild(arr, val, obj[arr[k]], k + 1)
}
function extractStringAndIndex(input: string) {
const regex = /^(\w+)\[(\d+)\]$/;
const match = input.match(regex);
if (match) {
const string = match[1];
const index = parseInt(match[2]);
return { string, index };
} else {
return null; // Not in the expected format
}
}
const intermediateObject = _.transform(
object,
(result, _value, key: any) => {
const pathArray = _.split(key, '.')
injectInChild(pathArray, result[key], result)
if (_.size(pathArray) > 1) delete result[key]
},
{ ...object }
)
_.each(_.keys(intermediateObject), (key, value) => {
const pair = extractStringAndIndex(key)
if (pair) {
if (_.isNil(intermediateObject[pair.string])) {
intermediateObject[pair.string] = []
}
intermediateObject[pair.string].push(intermediateObject[key])
_.unset(intermediateObject, key)
}
})
return intermediateObject
}
function convertObjectToPathObject(object: any) {
function extractFromPathObject(obj: any, parentKey = '') {
let result: any = {}
for (const key in obj) {
if (_.isObjectLike(obj[key])) {
if (_.isArray(obj[key])) {
// If it's an array, loop through each element
obj[key].forEach((value: any, index: number) => {
const arrayKey = `${parentKey ? `${parentKey}.${key}[${index}]` : `${key}[${index}]`}`;
if (_.isObjectLike(value)) {
const nestedObject = extractFromPathObject(value, arrayKey);
result = { ...result, ...nestedObject };
} else {
result[arrayKey] = value;
}
});
} else {
// If it's an object, recurse
const nestedObject = extractFromPathObject(obj[key], parentKey ? `${parentKey}.${key}` : key);
result = { ...result, ...nestedObject };
}
} else {
// Base case: non-object value
result[parentKey ? `${parentKey}.${key}` : key] = obj[key];
}
}
return result;
}
return extractFromPathObject(object);
}
console.log(convertObjectToPathObject(convertPathObjectToObject(object)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment