To achieve the desired outcome, a generic function can be created to extract the first child from an array or object:
function getFirstChild(data) {
if (Array.isArray(data)) {
return data[0];
} else {
return data[Object.keys(data)[0]];
}
}
By utilizing this function, the first level of nesting can be extracted by calling it three times consecutively:
// First level extraction
var myData = getFirstChild(data);
// Second level extraction
myData = getFirstChild(myData);
// Third level extraction
myData = getFirstChild(myData);
The variable myData
will then contain the desired value. While this approach works, there is always room for optimization and refinement.
Complete Code Snippet
function getFirstChild(data) {
if (Array.isArray(data)) {
return data[0];
} else {
return data[Object.keys(data)[0]];
}
}
var data = [
{
"Table":[
{
"id":1,
"DESC":"Sports",
"ORDER":1,
"AVAILABLE":true
},
{
"id":2,
"DESC":"Math",
"ORDER":2,
"AVAILABLE":true
},
{
"id":3,
"DESC":"English",
"ORDER":3,
"AVAILABLE":true
}
]
}
];
// First level extraction
var myData = getFirstChild(data);
// Second level extraction
myData = getFirstChild(myData);
// Third level extraction
myData = getFirstChild(myData);
console.log(myData);
If looping through an array is required, the function can be called twice instead of thrice:
function getFirstChild(data) {
if (Array.isArray(data)) {
return data[0];
} else {
return data[Object.keys(data)[0]];
}
}
var data = [
{
"Table":[
{
"id":1,
"DESC":"Sports",
"ORDER":1,
"AVAILABLE":true
},
{
"id":2,
"DESC":"Math",
"ORDER":2,
"AVAILABLE":true
},
{
"id":3,
"DESC":"English",
"ORDER":3,
"AVAILABLE":true
}
]
}
];
// First level extraction
var myData = getFirstChild(data);
// Second level extraction
myData = getFirstChild(myData);
console.log(myData);