How can I create a function to extract specific values from an array? The goal is to retrieve the values 4, 3, and 22 from the second column of 'selection1'.
var data =
{"selection1": [
{"answers": [1, 4, 5, 7]},
{"answers": [4, 3, 2, 1]},
{"answers": [10, 22, 12, 34]},
],
"selection2": [
{"answers": [31, 34, 35, 37]},
{"answers": [44, 43, 42, 41]},
{"answers": [20, 42, 22, 54]},
]};
I need to achieve this by using the function call:
get_column_from_object(1, data, 'selection1') // should return [4, 3, 22]
What steps do I follow in order to accomplish this task successfully?
This snippet demonstrates my progress so far:
var data = {
"selection1": [{
"answers": [1, 4, 5, 7]
}, {
"answers": [4, 3, 2, 1]
}, {
"answers": [10, 22, 12, 34]
}, ]
};
function get_column_from_object(col_num, arr, prop) {
var result = [];
for (i = 0; i < arr.length; i++) {
result.push(arr[i][prop].answers[col_num]);
}
return result;
}
var new_result = get_column_from_object(1, data, 'selection1');
document.getElementById("output").innerHTML = new_result;
<p id="output"></p>