There is no direct method to Flatten nested objects in JavaScript. You have to pull out all the values to a single depth using for loop and other methods.
Flatten nested object JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script >
let ob = {
C: "EHs",
A: "BN",
N: +91,
M: {
HTML: "MR ABC",
CSS: "XYZ",
JS: "NONE"
}
};
const flattenObj = (ob) => {
let result = {};
for (const i in ob) {
if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
const temp = flattenObj(ob[i]);
for (const j in temp) {
result[i + '.' + j] = temp[j];
}
}
else {
result[i] = ob[i];
}
}
return result;
};
console.log(flattenObj(ob));
</script>
</body>
</html>
Output:
Another example
function flattenObject(obj, newObj, prefix) {
newObj = newObj || {};
prefix = prefix || "";
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
const type = typeof obj[key];
const newKey = !!prefix ? prefix + "." + key : key;
if (type === "string") {
newObj[newKey] = obj[key];
}
else if (type === "object") {
flattenObject(obj[key], newObj, newKey);
}
}
}
return newObj;
}
var obj = {
name:'Namig',
surname:'Hajiyev',
address:{
city:'Sumgait',
country:'Azerbaijan',
geo: {
lat:'40.5897200',
long:'49.6686100'
}
}
}
console.log(flattenObject(obj));
Output:
{
"name": "Namig",
"surname": "Hajiyev",
"address.city": "Sumgait",
"address.country": "Azerbaijan",
"address.geo.lat": "40.5897200",
"address.geo.long": "49.6686100"
}
Using Recursion
const source = {
a: 1,
b: {
c: true,
d: {
e: 'foo'
}
},
f: false,
g: ['red', 'green', 'blue'],
h: [{
i: 2,
j: 3
}]
}
const flatten = (obj, prefix = '', res = {}) =>
Object.entries(obj).reduce((r, [key, val]) => {
const k = `${prefix}${key}`
if(typeof val === 'object'){
flatten(val, `${k}.`, r)
} else {
res[k] = val
}
return r
}, res)
console.log(flatten(source))
Output:
{
"a": 1,
"b.c": true,
"b.d.e": "foo",
"f": false,
"g.0": "red",
"g.1": "green",
"g.2": "blue",
"h.0.i": 2,
"h.0.j": 3
}
Do comment if you have any doubts or suggestions on this Js example code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version