Created
August 29, 2013 14:54
-
-
Save kamranayub/6379147 to your computer and use it in GitHub Desktop.
Remove the root element of a JSON object, see: http://jsfiddle.net/kamranayub/72dm2/
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
var rootElementJson = { | |
root: { | |
name: "Foo", | |
person: true | |
} | |
}; | |
var removeRootElement = function (obj) { | |
var numKeys = 0, | |
rootKey; | |
// Iterate through keys in object and confirm there's only a single root | |
for (var key in obj) { | |
// Skip built in | |
if (!obj.hasOwnProperty(key)) continue; | |
// Assign current key as root | |
rootKey = key; | |
// Increment key counter | |
numKeys++; | |
// Stop if there's more than one key | |
if (numKeys === 2) { break; } | |
} | |
// If there is a single root, transfer its contents (if applicable) to | |
// a new object to return | |
if (numKeys === 1) { | |
var newObj = {}, | |
rootObj = obj[rootKey]; | |
if (typeof rootObj === "object") { | |
for (var key in rootObj) { | |
if (rootObj.hasOwnProperty(key)) { | |
newObj[key] = rootObj[key]; | |
} | |
} | |
return newObj; | |
} | |
} | |
return obj; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment