Created
June 4, 2019 14:45
-
-
Save cbarley10/0796e7d2f3da5d1cba5c187c83eed56a to your computer and use it in GitHub Desktop.
Flatten an Object
This file contains 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
const flatten = require("flat"); | |
const dogs = { | |
dog1: { | |
name: "Bailey", | |
breed: "Lab", | |
age: 3, | |
best_friend: { | |
name: "Vinny", | |
breed: "Golden Retriever", | |
age: 3 | |
} | |
}, | |
dog2: { | |
name: "Vinny", | |
breed: "Golden Retriever", | |
age: 3, | |
best_friend: { | |
name: "Bailey", | |
breed: "Lab", | |
age: 3 | |
} | |
} | |
}; | |
const flatten1 = obj => { | |
let newObj = {}; | |
for (let i in obj) { | |
if (typeof obj[i] === "object") { | |
let flat = flatten1(obj[i]); | |
for (let j in flat) { | |
newObj[i + "." + j] = flat[j]; | |
} | |
} else { | |
newObj[i] = obj[i]; | |
} | |
} | |
return newObj; | |
}; | |
const flatten2 = obj => flatten(obj); | |
console.log("Flatten with vanilla JS:\n", flatten1(dogs)); | |
console.log("==============================================="); | |
console.log("Flatten with flat package:\n", flatten2(dogs)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment