Creating a custom function that retrieves a specific column from a JSON object and returns it as an array

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>

Answer №1

Shoutout to Barmar for providing the perfect solution

<p id="demo"></p>

<script>
var data = {"category1": [{"answers": [8, 9, 3, 2]}, {"answers": [7, 5, 1, 6]},{"answers": [21, 14, 32, 18]}, ]};

function extract_specific_column(col_num, obj, prop) {
  var results = [];
  var arr = obj[prop];
   for (i = 0; i < arr.length; i++) {
     results.push(arr[i].answers[col_num]);
     }
  return results;
}


var fresh_data = extract_specific_column(2, data, 'category1');
document.getElementById("demo").innerHTML = fresh_data;

</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing distinct jQuery event listeners on the parent div and the button within

I am facing an issue with a button inside a list row that is used to delete the row from the page. The row is also bound to a click event that redirects to another page. This setup is causing problems as clicking the inner button triggers the containing ro ...

Troubleshooting jQuery and Mootools compatibility problem in Internet Explorer 8

I am currently working on a webpage that is using both Mootools 1.4 and jQuery 1.5.1 at the same time. I understand that this setup is not ideal, but for various reasons, I have no choice in the matter. Most browsers display the page without any issues, ho ...

Error: The 'ActivitiesClient' object does not contain a property named 'base_url'

Although this question may have been answered before, I have not been able to identify my mistake despite searching through numerous questions. Here is my script: import json from config import BASE_URL from utils.request import APIRequest class Activi ...

JavaScript Array Objects

As a newcomer to the world of Javascript, I've decided to take on the challenge of creating a blackjack game. Utilizing arrays and objects for my game: card = {}, //each card is represented as an object with suit, number, and points properties playe ...

PHP project encountered an error stating: "Uncaught TypeError: Ajax is not a function"

I am in the process of configuring an apache server for a project using XAMPP, MySQL, and PHP 5.6 Unfortunately, it appears that there is an issue with how JavaScript has been referenced in the project, and I am unable to get it to function correctly (th ...

JavaScript: Techniques for extracting multiple digits from a text

Enter: "WASHINGTON (Reuters) U.S. stock index futures indicated a marginal recovery on Wall Street on Thursday, as futures for the S&P 500 rose by 0.34 percent, Dow Jones futures gained 0.12 percent, and Nasdaq 100 futures increased by 0.51 percent ...

Ways to extract particular keys from a JSON array?

I am receiving an array of JSON objects in my response. {"took":0,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{" ...

Angular 2 with a jssor slider that adjusts seamlessly to different screen

After following the guidance provided in this answer on incorporating jssor into angular2, I have implemented the following JavaScript code snippet in a file and referenced it in angular-cli.json. jssor_1_slider_init = function() { var jssor_1_op ...

Difficulty activating JavaScript function - unsure of proper implementation

I'm having trouble with calling a function instead of an alert in my code. I tried using FunctionsName(); and removing the alert(''); but it doesn't seem to be working for me :( Could someone please take a look at the following code an ...

Issue with updating patch version using NPM standard-version

I have integrated standard-version into my javascript project. I made sure to include the release script in my package.json: "scripts": { ... "release": "standard-version" } However, after adding a commit with the mes ...

The Controller received a JSON object that was empty

I know this question has been asked countless times, but I've tried all solutions with no success. Here's the JSON object in question: { "manufacture":"HP", "model":"testModel", "serialNumber":"testSerial", "description":"Test Descript ...

Changing profile picture using React UI framework

I'm just starting with react so please bear with me if I make any mistakes. I am trying to figure out how to update a user's profile picture. I need to create a clickable image (with the variable name "avatar" in the code) that will show a previe ...

Using focusout and clicking buttons do not effectively interact with child elements

I have a series of div elements, each containing a button. When I click on a button, text is displayed, and when I click away, the information hides with a focus-out function. If I have one button open and then want to click on another parent button, it wo ...

Pointer Mouse Script

I'm in the process of figuring out the coding behind the mouse pointer effect used in the header of this particular wordpress template: Despite my efforts, I am having trouble pinpointing the specific script responsible for this effect. Could it poss ...

Using AngularJS to extract data from a JSON feed that contains a namespace

Just diving into Angular and I'm loving it. Struggling with parsing a JSON feed that has namespaces, need some help: Here's an example from the JSON feed: "title": { "label": "Fuse" }, "im:name": { "label": "John Doe" }, "im:image": [ { ...

Adding supplementary documents within the app.asar file via electron

This is a Vue application using electron-builder. { "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "electron:build": "vue-cli-service electron:build", "electron:serve": "vue-cli-service electron:serve", ...

The Mechanism of the Length Function in Contemporary Programming Languages

In most modern programming languages, determining the length of an iterator, list, array, or string is a straightforward task. Typically, this involves using a len() method in languages like Python or accessing a .length property in JavaScript. However, I ...

Caution: Server Components can only pass plain objects to Client Components

My app allows users to search for care homes on a map and add new ones using a form. During development, everything was working fine. However, in production, the map was not updating to show the newly added care homes. It seemed that the API fetching the ...

Tips for generating an auto-incremented ID column in jQuery tables through the render method

My jQuery Datatable setup looks like this let purchasedProductTbl = $('#grdPurchasedProduct').DataTable({ filter: false, paging: false, lengthChange: false, searching: false, ordering ...

Winning awards through the evaluation of possibilities

I became intrigued by the idea of using a chance algorithm to simulate spinning a wheel, so I decided to create some code. I set up an object that listed each prize along with its probability: const chances = { "Apple" : 22.45, & ...