Skip to content

Instantly share code, notes, and snippets.

@mohit-s96
Last active June 11, 2021 08:43
Show Gist options
  • Select an option

  • Save mohit-s96/0930006174e88327d51b30980a3889d5 to your computer and use it in GitHub Desktop.

Select an option

Save mohit-s96/0930006174e88327d51b30980a3889d5 to your computer and use it in GitHub Desktop.
Flatten array of objects in javascript
// Recursive flatten function (Doesn't flatten arrays)
function flatten(obj, target){
for(const key in obj){
if(obj.hasOwnProperty(key)){
if(!Array.isArray(key) && typeof(obj[key]) === "object" && obj[key] !== null){
flatten(obj[key], target);
}else{
target[key] = obj[key];
}
}
}
return target;
}
// Example usage
(async () => {
const data = await fetch("https://randomuser.me/api/?results=5");
const json = await data.json();
console.log(json.results.map(x => flatten(x.location, {})))
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment