Remove Root Key in JSON
Removes the root key in a JSON object
HTML
<div id="log"></div>
JavaScript
var rootElementJson = {
{"result":[[{"id":1,"cedula":"34546","nombres":"456546"}]]}
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;
};
document.getElementById("log").innerText = JSON.stringify(removeRootElement(rootElementJson));