Skip to content

Instantly share code, notes, and snippets.

@donavon
Created February 28, 2022 02:40
Show Gist options
  • Save donavon/f94b2dd6a619ce08a523194662d93313 to your computer and use it in GitHub Desktop.
Save donavon/f94b2dd6a619ce08a523194662d93313 to your computer and use it in GitHub Desktop.
JS Quiz #2
/*
Write a function to flatten any object such that the flatten keys are a camelCased
concatination of the key and all parent keys. If the value is an array, name the key with the
position of the array (base 1) and remove the plural "s" (assume all arrays end with an "s").
Should work with infinite layers, not just two. Arrays can contain objects.
In the example `user` below, the output would be as follows:
{
nameFirst: 'John',
nameLast: 'Doe',
mailingAddressLine1: '100 M Main',
mailingAddressLine2: 'Apt 2B',
mailingAddressCity: 'Anytown',
mailingAddressState: 'USA',
mailingAddressZip: '01001',
email: '[email protected]',
};
You can use this utility function to check if a variable is an object:
const isObject = (obj) => typeof obj === 'object' && !!obj;
*/
const user = {
name: {
first: 'John',
last: 'Doe',
},
mailingAddress: {
lines: ['100 M Main', 'Apt 2B'],
city: 'Anytown',
state: 'USA',
zip: '01001',
},
email: '[email protected]',
};
const flattenObj = (obj) => {
// your code here
};
const flattenedObj = flattenObj(user);
console.log(flattenedObj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment