Created
May 22, 2023 04:32
-
-
Save dorman99/b3af3d34a427cdf5a2ddd587a30d3f67 to your computer and use it in GitHub Desktop.
nested object handler
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
// "Given any JSON object. Please write a function to convert it to dot-notation object. | |
// { | |
// ""key"": { | |
// ""value1"": 100, | |
// ""value2"": 200, | |
// ""nested"": { | |
// ""inside"": true | |
// } | |
// } | |
// } | |
// => { ""key.value1"": 100, ""key.value2"": 200, ""key.nested.inside"": true }" | |
const dataRequest = { | |
key1: { | |
value1: 100, | |
value2: 200, | |
nested: { | |
inside: true, | |
}, | |
}, | |
key2: { | |
value1: 110, | |
value2: 200, | |
nested2: { | |
inside: false, | |
}, | |
nested3: { | |
inside: true, | |
}, | |
}, | |
key3: { | |
value1: 110, | |
value2: 200, | |
nested2: { | |
inside: false, | |
}, | |
nested3: { | |
inside: true, | |
key2: { | |
value1: 110, | |
value2: 200, | |
nested2: { | |
inside: false, | |
}, | |
nested3: { | |
inside: true, | |
}, | |
}, | |
}, | |
}, | |
}; | |
function dotNotation(request) { | |
const dataList = []; | |
const response = {}; | |
for (key in request) { | |
findKey(key, request[key], dataList); | |
} | |
for (let i = 0; i < dataList.length; i++) { | |
response[dataList[i].key] = dataList[i].data; | |
} | |
return response; | |
} | |
function findKey(parentKey, request, data) { | |
for (key in request) { | |
currentKey = key; | |
currentData = request[currentKey]; | |
if (typeof currentData == "object") { | |
let res = findKey((parentKey += `.${key}`), currentData, data); | |
if (res) { | |
data.push(); | |
} | |
} else { | |
data.push({ key: `${parentKey}.${currentKey}`, data: currentData }); | |
} | |
} | |
return data; | |
} | |
const result = dotNotation(dataRequest); | |
console.log({ result }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment