Created
April 29, 2015 14:11
-
-
Save bjoerge/f8e492d61c0f3b7e5335 to your computer and use it in GitHub Desktop.
Recursively skip keys with no siblings
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 assert = require("assert"); | |
function skipSingleKeys(obj) { | |
if (obj === null || typeof obj !== 'object') { | |
return obj; | |
} | |
const keys = Object.keys(obj); | |
if (keys.length == 1) { | |
return skipSingleKeys(obj[keys[0]]); | |
} | |
return keys.reduce((acc, key) => { | |
acc[key] = skipSingleKeys(obj[key]) | |
return acc; | |
}, {}); | |
} | |
const object = { | |
norge: { | |
fylker: { | |
oslo: { | |
navn: "Oslo", | |
kommuner: { | |
oslo: { | |
navn: "Oslo" | |
} | |
} | |
}, | |
akershus: { | |
navn: "Akershus", | |
kommuner: { | |
ski: { | |
navn: "Ski" | |
}, | |
asker: { | |
navn: "Asker" | |
} | |
} | |
} | |
} | |
} | |
}; | |
assert.deepEqual(skipSingleKeys(object), { | |
oslo: { | |
navn: "Oslo", | |
kommuner: "Oslo" | |
}, | |
akershus: { | |
navn: "Akershus", | |
kommuner: { | |
ski: "Ski", | |
asker: "Asker" | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment