Exploring the Fusion of Data in VueJS

Trying to figure out how to merge data from two different sources to display in a single table. One source is created within my Vue instance, while the other is imported from an API. Any suggestions on how to achieve this?

HTML:

 <div class="ui container" id="app">
  <br>
  <div class="ui two column divided grid">
    <div class="row">
      <div class="ten wide column">
        <table class="ui unstackable green table">
          <thead>
            <tr>
              <th>Instrument</th>
              <th class="right aligned">Position</th>
              <th class="right aligned">Price</th>
              <th class="right aligned">Total</th>
              <th class="right aligned">%</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in watchlist">
              <td>{{ item.instrument }}</td>
              <td class="right aligned">{{ item.position }}</td>
              <td class="right aligned"></td>
              <td class="right aligned"></td>
              <td class="right aligned"></td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="six wide column" :attribute="priceData">
        <table class="ui unstackable red table">
          <thead>
            <tr>
              <th  class="center aligned">Coin</th>
              <th  class="center aligned">Price</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="coin in prices">
              <td>{{ coin.name }}</td>
              <td class="center aligned">{{ coin.price_usd }}</td>
            </tr>
          </tbody>
      </table>
      </div>
    </div>
  </div>
</div>

Currently, I have two separate tables displaying data that I want to merge into a single table.

Vue:

      new Vue({
    el: '#app',
    data: {
      watchlist: [
        {  instrument: 'Artbyte', position: 10000 },
        {  instrument: 'Civic (CVC)', position: 1000 },
        {  instrument: 'IOTA', position: 600 },
        {  instrument: 'Basic Attention Token', position: 600 },
        {  instrument: 'Sentiment (SAN)', position: 500 },
        {  instrument: 'TenX', position: 400 },
        {  instrument: 'OmiseGo', position: 100 },
        {  instrument: 'EOS', position: 200 },
        {  instrument: 'Litecoin', position: 30 },
        {  instrument: 'Ethereum', position: 10 },
        {  instrument: 'Bitcoin', position: 2 },
        {  instrument: 'District0x', position: 2000 },
        {  instrument: 'Aragon', position: 60 },
        {  instrument: 'LBRY Credits', position: 200 }
      ],
      prices: []
    },
    computed: {
      priceData: function () {
        var t = this
        axios.get('https://api.coinmarketcap.com/v1/ticker/')
          .then(function (response) {
            t.prices = response.data
          })
          .catch(function (error) {
            console.log(error)
          })
      },
      getPrices: function () {
        return this.price
      }
    }
  })

Check out this code snippet on JSFiddle

Answer №1

priceData should not be a computed property; it does not have a return value. It should be executed in the created lifecycle hook.

To combine the data from two sources, you can create a computed property like this:

    created() {
        var temp = this
        axios.get('https://api.coinmarketcap.com/v1/ticker/')
          .then(function (response) {
            temp.prices = response.data
          })
          .catch(function (error) {
            console.log(error)
          })        
    },
    computed: {
      combinedData() {
          return this.prices.map(currency => {
              var newObj = Object.assign({}, currency);
              var item = this.watchlist.find(watchItem => watchItem.instrument === newObj.name);
              if (item) {
                  Object.assign(newObj, item);
              }
              return newObj;
          });
      }
    },

The map function creates a new array by copying each item in prices, searching for a corresponding item in watchlist (based on matching instrument in the watchlist item and name in the prices item), and if found, merges the fields from the watchlist item into the new object.

In essence, it generates a new array with items from prices where relevant watchlist items are integrated into them (if matching items exist).

Check out the updated JSFiddle here

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

Trigger a Vue update upon detecting a new ID in the URL

Within my Vue2 application, I have implemented the use of the id parameter within a component that occupies the primary view. For example, http://localhost:8080/#/basereports/watercombochart/129 This URL signifies that the chart with id settings correspon ...

What is the best way to include JSX in a separate HTML file?

Currently developing a PWA using create-react-app. Upon inspecting the index.html page, I realized there are no links to any JS files, leading me to assume that CRA injects JSX into the 'root' div of index.html. Now, my goal is to include an offl ...

Mixing pipe operators with Angular Observables in an array

In my project, I have an interesting scenario where I am using Observables and piping them to multiple functions as shown below. getOrders(filters: any, page: any = 1, orderBy: string = 'deliver_on', sort: string = 'asc') { const op ...

What is the best way to showcase a set of paired arrays as key-value pairs?

Currently, I am developing a client in React that is responsible for receiving streaming data that represents objects from the back end. The client's task is to parse this data and dynamically construct the object as a JavaScript data structure, typic ...

"Delve into the art of utilizing negative space between elements with

Looking to implement hover detection between rows in a grid container, rather than on individual items. The number of items in the container and per row may vary. https://i.sstatic.net/yBgKI.png It's important to note that the item count in the cont ...

Using ReactJS and JavaScript to transform an array into a fresh array

I am working with an array that looks like this: var oldArray = [ {number: '12345', alphabet: 'abcde'}, {number: '54321', alphabet: 'abcde'}, {number: '67891', alphabet: 'abcde'}, ...

Guide: Utilizing JSON API data to generate marker labels on a leaflet map

Users are presented with points to click on. When a point is clicked, a menu displays text information. I have successfully placed the points, but when attempting to retrieve specific data from the database upon clicking a point, it does not show the marke ...

How to choose a javascript drop down using selenium?

Here is the HTML code for a JavaScript drop-down menu that contains various options, including "All Resumes". I am attempting to select this option using Selenium WebDriver: <div id="resume_freshness_container"> <div class="dropdown_small_wrapper ...

Do not reload the page after a successful ajax request

I'm using an Ajax section to submit data in Laravel. I want the page to not reload if the submission is successful, but to reload if there's an error. Currently, when there is an error, the page reloads correctly. However, I'm facing an issu ...

Different Vue sorting libraries to choose from

Currently, I am in the process of sorting data on the frontend while utilizing VueJS within my application. Instead of developing the logic for sorting from scratch, I am interested in knowing if there are any libraries available that can assist with this ...

Personalized style for text overflow property

The application is created using Angular. Within a component, we have a div containing some text: <div>abcdefghijklmnop<div> Depending on the screen size, the text should either be fully displayed or clipped. I discovered the property 'te ...

What is causing myInterval to not be cleared properly?

const homeButton = document.getElementById('home'); window.myInterval = 0; const showHome = () => { console.log('showHome'); window.myInterval = setInterval(wait, 400) } const wait = () => { console.log('wait'); ...

Guide to storing data in the browser's local storage with a Node.js Express backend

Up until this point, I relied on cookies to store preferences for my websites. However, as time has passed, the data stored in these cookies has grown too large and now exceeds the limit of 4096 characters. Therefore, I need to explore an alternative meth ...

Utilizing $index in AngularJS while iterating through ng-repeat items

Here is an example of an unordered list: <ul class="dropdown-menu inner" role="menu"> <li ng-repeat="availableAlphaName in availableAlphaNames" data-original-index="0" data-optgroup="1" class=""> <a tabindex="0" class="opt " st ...

Guide on excluding a specific element using an Xpath expression

I am seeking a solution to craft an XPath expression that can target all <p> elements except for p[6] and p[7]. Currently, I have formulated this expression: //div[@class="Job-Description app-responsive-jd"]/p[1], which is functioning corre ...

What is the best way to collapse a button in asp.net using javascript after setting it to hidden?

I have a scenario where I have 3 buttons in a row on my asp.net page. Using JavaScript, I am setting the middle button (ButtonSR) to invisible. However, I want the button below it to move up and take its place instead of leaving an empty space. ...

The page you are looking for cannot be located using Jquery AJAX JSON PHP POST -

Whenever I attempt to POST some JSON data to a local host, I consistently encounter a 404 Not Found error. Strangely enough, the php file is positioned precisely where it should be according to the script instructions. If anyone has dealt with this issue b ...

What is the proper method for implementing an event listener exclusively for a left mouse click?

Is there a way to make Phaser recognize only left mouse clicks as click events, excluding right and middle clicks? Check out this Phaser example at the following link: https://phaser.io/examples/v2/basics/02-click-on-an-image. ...

Uncovering secret divs with the power of jQuery timing upon reload

Currently, I am in the process of developing a custom Wordpress theme for my blog which includes an overlay-container. When a button is clicked, this container slides in from the top and pushes down the entire page. To achieve this functionality, I am uti ...

While experimenting with p5.js, I encountered an issue where I received the error message stating that "loadAnimation is not defined and createSprite not defined." This problem persists even when using VSCode

let background, sleeping, brushing, gyming, eating, drinking, moving, astronaut; function preload() { background = loadImage("images/iss.png"); sleeping = loadAnimation("images/sleep.png"); brushing = loadAnimation("images/ ...