What is the best way to iterate through a designated key in every object within a JSON dataset and store it in a variable called `data` for use with

I am looking to create a line chart displaying stock prices, utilizing JSON data to populate the chart.

Let's say I have some JSON data:

[
    {
    "close": 116.59,
    "high": 117.49,
    "low": 116.22,
    "open": 116.57,
    "symbol": "AAPL",
    "volume": 46691331,
    "id": "HISTORICAL_PRICES",
    "key": "AAPL",
    "date": "2020-11-27",
  },
  // { ... }
]

Next step is to implement the following code using chart.js:


<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Jan', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 29, 3, 5, 1, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                stacked: true
            }
        }
    }
});
</script>

If I want to extract the 'close' key (representing price) from each index in the JSON data and use it in the dataset's data section below, how would I achieve that?

Answer №1

To extract the close property value from each object in the JSON array, you can iterate through the array and store the values in a new array variable.

Here is an example:

var arr = [
    {
        "close": 116.59,
        "high": 117.49,
        "low": 116.22,
        "open": 116.57,
        "symbol": "AAPL",
        "volume": 46691331,
        "id": "HISTORICAL_PRICES",
        "key": "AAPL",
        "date": "2020-11-27",
    },
    {
        "close": 114.59,
        "high": 117.49,
        "low": 116.22,
        "open": 116.57,
        "symbol": "AAPL",
        "volume": 46691331,
        "id": "HISTORICAL_PRICES",
        "key": "AAPL",
        "date": "2020-11-27",
    },
    {
        "close": 11.59,
        "high": 117.49,
        "low": 116.22,
        "open": 116.57,
        "symbol": "AAPL",
        "volume": 46691331,
        "id": "HISTORICAL_PRICES",
        "key": "AAPL",
        "date": "2020-11-27",
    }
];

var dataset = [];

arr.forEach((value, key)=>{
    dataset.push(value.close);
});

console.log(dataset);

Answer №2

let stockData = [
    {
        "close": 116.59,
        "high": 117.49,
        "low": 116.22,
        "open": 116.57,
        "symbol": "AAPL",
        "volume": 46691331,
        "id": "HISTORICAL_PRICES",
        "key": "AAPL",
        "date": "2020-11-27"
    },
    {
        "close": 105.3,
        "high": 117.49,
        "low": 116.22,
        "open": 116.57,
        "symbol": "AAPL",
        "volume": 46691331,
        "id": "HISTORICAL_PRICES",
        "key": "AAPL",
        "date": "2020-11-27"
    }
];

let closingPrices = stockData.filter(item => item?.close).map(item => item.close);

console.log(closingPrices);

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

Verifying the accuracy of the JSON response

After receiving a JSON response from my server, I am faced with the challenge of determining if the response is correct or incorrect. Below, you can see an example test case I have created. { "@type": "res", "createdAt": "2014-07-24T15:26:49", ...

Encountering an issue with reading JSON string values in IOS Swift

I am currently retrieving data from a URL in JSON format. My goal is to color a specific button blue if a certain JSON column does not contain null or Nil. Here is an example of the JSON structure: {"votes":"0","vote_status":null},{"votes":"1","vote_statu ...

Is there a way to create a dynamic gallery using Magnific Popup that showcases both images and an iframe video together?

One way I am utilizing magnific popup is to set up an image gallery using the code snippet below: $('.main-content').magnificPopup({ delegate: '.gallery', // selecting child items to open in pop-up when clicked type: 'image&ap ...

``Protect your PDF Document by Embedding it with the Option to Disable Printing, Saving, and

Currently, I am facing a challenge to enable users to view a PDF on a webpage without allowing them to download or print the document. Despite attempting different solutions like Iframe, embed, PDF security settings, and Adobe JavaScript, I have not been s ...

When you use Array.push, it creates a copy that duplicates all nested elements,

Situation Currently, I am developing a web application using Typescript/Angular2 RC1. In my project, I have two classes - Class1 and Class2. Class1 is an Angular2 service with a variable myVar = [obj1, obj2, obj3]. On the other hand, Class2 is an Angular2 ...

Oops! Looks like there was an error. The text strings need to be displayed within a <Text> component in the BottomTabBar. This occurred at line 132 in the

My app includes a bottomTab Navigation feature, but I encountered an error: Error: Text strings must be rendered within a <Text> component. This error is located at: in BottomTabBar (at SceneView.tsx:132) in StaticContainer in StaticCont ...

Problem with Google's PageSpeed Insights - Focus on Making Most Important Content Visible

During the process of creating a comprehensive website for a client who has a strong affinity towards Google tools and recommendations, I have encountered an interesting challenge: Despite my best efforts, I seem unable to attain a flawless score for the ...

How can the datetime value of the Apex Charts datapoint be shown in the tooltip?

I'm struggling to find the proper location within the w.globals object to display the x-axis value, which is a datetime, in the tooltip of the datapoint. var chartOptions = { ... xaxis: { type: "datetime" }, tooltip: { x: { format: " ...

Improved method for transferring multiple form input values from a child to a parent window

I am working on a project where I have a child window containing multiple radio buttons. My goal is to send all the selected values from these radio buttons to the parent window. Currently, I am achieving this by creating a JavaScript string that contains ...

Combine various JSON files into a single array

I am currently facing an issue with reading two JSON files in my array. I have tried different methods but haven't found a solution yet. Is there a way to combine these JSON files into one array? One method I attempted was storing both JSON files in ...

Tips for converting a QR code to data URL encoding to include in a JSON response

I created a nodejs function to encode a QR code and I want to return the result back to the caller function in order to create a JSON response. However, for some reason my code is not returning the data response. Can someone please help me figure out what& ...

Tips for retrieving specific data from a variable in an object using PHP

I am facing a challenge in accessing the value of an object with an array in PHP Laravel. Currently, I have successfully accessed the information using the following method. However, the issue arises when the position of the required information changes, f ...

Understanding the process of extracting a list of strings from a JSON file in Scala

val dataFrame = spark.read.option("multiline", "true").json("/FileStore/tables/config-5.json") dataFrame.show() Output: +--------------+-------------------+ | List-col| Matrics| +--------------+---------- ...

Unable to bring in the specified export 'Directive' from a non-EcmaScript module - only the default export is accessible

I am currently working on an ionic angular project and utilizing the ng-lazyload-image plugin. However, I am encountering errors during compilation that look like this: Error: ./node_modules/ng-lazyload-image/fesm2015/ng-lazyload-image.mjs 401:10-19 Can ...

How can I set up mixare with JSON data?

$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban"; $q=mysqli_query($connection, $query); // Assume $connection is the MySQL connection variable //echo $query; while($row=mysqli_fetch_assoc( ...

Save pictures in MongoDB using GridFS or BSON format

As a newcomer to MongoDB, I am seeking advice on the best way to store images in the database. Gridfs and BSON seem to be the most common options, but I'm unsure about their respective pros and cons. The main difference I'm aware of is the 16MB s ...

Using PHP's json_encode function to structure array data with square brackets [] is a helpful way to

Purpose: Find a solution to correctly format array data using json_encode The desired format for the data post PHP json_encode transformation is specified below: EXPECTED FORMAT { "top_level_data": [ { "extension": {}, "sub_leve ...

Having trouble generating a JSON file from user input upon clicking the button in a C# Windows Form application

Currently, I am in the process of developing a C# application using VS2017 windows form application. The primary functionality of this app is to take user input and save it into a JSON file. However, there's a limitation where only one user input can ...

Notify user with a Javascript alert if there are no search results found

I have developed a search index for Chicago employees and want to create an alert if no matching records are found. However, I am struggling to determine the value that needs to be inserted in case of an empty result set. Ideally, upon submission of the fu ...

Having trouble with Jquery's Scroll to Div feature?

When I click on the image (class = 'scrollTo'), I want the page to scroll down to the next div (second-container). I've tried searching for a solution but nothing seems to work. Whenever I click, the page just refreshes. Any help would be gr ...