What is the best way to convert the data stored in an object to an array?

I have a function that is constantly checking for temperature data:

{"a":"43",
"b":"43",
"c":"42",
"d":"43",
"e":"40",
"f":"41",
"g":"100",
"h":"42.6"}

My goal is to graph this data over time, but I'm struggling with how to structure it to fit the format I need:

temps: [{
    name: "a",
    data: ["43","42","43"]
  },
    name: "b",
    data: ["43","42","43"]
  },
    etc...
  ]

I attempted the code below and tried using the JavaScript map function, but I encountered issues with scoping where "this" was not referencing the same object as in the parent:

this.temp_names.forEach(function(e){
    if(typeof this.temps[e] == "undefined") {
      this.temps[e] = []
    }
    this.temps.e.unshift(this.sys_telemetry.S.temps)
    if (this.temps.e.length > 10) {
      this.temps.e.pop()
    }
})

The "temp_names" array contained all the keys needed for mapping.

I am working on this within VueJS, where "this" corresponds to the data in my component.

Answer №1

By utilizing Array#from, Object#entries, Array#map, and destructuring, you can achieve the following.

const data={"a":"43","b":"43","c":"42","d":"43","e":"40","f":"41","g":"100","h":"42.6"}

const res = Object.entries(data)
.map(([name, data])=>({name, data:[data]}));

console.log(res);

Another approach using Array#reduce, Map,

const data={"a":"43","b":"43","c":"42","d":"43","e":"40","f":"41","g":"100","h":"42.6"}

const res = Array.from(Object
.entries(data)
.reduce((a,[k,v])=>{
  if(!a.has(k)) a.set(k, []);
  a.get(k).push(v);
  return a;
}, new Map()))
.map(([name, data])=>({name, data}));

console.log(res);

Answer №2

create a line graph showcasing the changes over time

To achieve this progression, it is recommended to generate an array and then utilize methods such as Object.entries, and Array.find to update the outcomes.

Below is an illustration.

const values1 = 
  {"a":"43", "b":"43", "c":"42", "d":"43", "e":"40", "f":"41",
  "g":"100", "h":"42.6"};
  
const values2 = 
  {"c":"44", "e":"39"};
  

const results =  [];

function addData(data) {
  Object.entries(data).forEach(([k, v]) => {
    let find = results.find(f => f.name === k);
    if (!find) {
      find = {
        name: k,
        data: []
      }
      results.push(find);
    }
    find.data.push(v);
  });
}

addData(values1); //data packet one arrives
addData(values2); //data packet two arrives
  
console.log(results); //results contains both data packet one & two.

Answer №3

To simplify your data structure, you could consider using an object like

{ a: [43, 42, 43], b: [1, 2, 3] }
instead of having separate keys for name and data.

If your initial data is in the form of

[{ a: 43, b: 1, c: 3 }, { a: 42, b: 2, c: 3 }]
, you can transform it into the previous format by looping through each data point:

const output = {};

temp_data.forEach(x => {
  for (const key in x) {
    const y = x[key];

    if (typeof output[key] === 'undefined') {
      output[key] = [];
    }

    output[key].push(y);
  }
});

This results in an object with keys matching the original data keys ("a", "b", "c", etc) and values as arrays of corresponding values, suitable for creating a timeline.

(For graph plotting, make sure to use numerical values like 1, 2, 3 instead of strings like "1", "2", "3".)

While there are more elegant ways to achieve this using functional programming techniques, this method should suffice!

Answer №4

It appears that there is a desire to add multiple datasets to the data object. One potential solution involves implementing a data object with methods that are capable of adding data to themselves. This could involve maintaining an internal index property, which should ideally be kept private and possibly sorted to ensure consistent ordering regardless of input order.

var data0 = {"a":"43",
"b":"43",
"c":"42",
"d":"43"};

var data1 = {"a":"53",
"b":"53",
"c":"52",
"d":"53",
"e":"65"
};

class DataObject {

  constructor (data) {
    this.index = [];
    this.data = [];
    if (data) {
      this.addData(data);
    }
  }

  addData (data) {
    Object.keys(data).forEach(key => {
      let idx = this.index.indexOf(key);
      if (idx == -1) {
        idx = this.index.push(key) - 1;
        this.data.push({name:key, data:[]});
      }
      this.data[idx].data.push(data[key]);
    });
  }
}

// Initialize object with some initial data
let myData = new DataObject(data0);
console.log(JSON.stringify(myData.data));

// Add additional data
myData.addData(data1);
console.log(JSON.stringify(myData.data));

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

Trouble with CSS loading due to div in Visual Studio MVC

Currently, I am working with Visual Studio 2013 MVC and have a situation regarding the styling of my navbar in _Layout. The navbar includes a messages dropdown menu that utilizes CSS and JS extensively. Interestingly, when I load the messages as a partial ...

What steps can I take to ensure my CSS component remains unaffected by the global CSS styles?

My navbar component is not displaying the styles correctly as intended. I have a Navbar.module.css file to style it, but after using next-auth for social login, only the buttons remain unstyled while everything else gets styled. The code snippet for impor ...

Javascript/AJAX functions properly on the homepage, but encounters issues on other pages

For a client, I have recently created 4 websites using Wordpress. Each site includes a sidebar with a script that utilizes the Google Maps API to estimate taxi fares. Strangely, the script works perfectly on the home page of each site, but fails to funct ...

What methods can I use to obtain negative numbers through swipe detection?

In my code, I am using three variables. The first one is x which serves as the starting point, followed by myCount which counts the number of swipes a user performs, and finally, dist which calculates the distance from the initial point. I want to set myC ...

`Only firing event listener once`

I have created a JS module where I am adding a click event to all links that match a specific selector. Here is an example of how it's done: var Lightbox = (function () { var showLightbox = function () { // this does stuff }; var init = fu ...

The time zones between Node 8 and Node 11 are not the same

Executing a basic new Date().toString() command produces different results on Node 11 compared to Node 8. In Node 11, the output includes the full timezone abbreviation like this: 'Fri May 10 2019 10:44:44 GMT-0700 (Pacific Daylight Time)' On t ...

Distinct "namespaces" within HTML

Recently, I've encountered an issue with my application that is causing ID collisions. The application uses AJAX to dynamically load code snippets based on user demand. Although these snippets vary significantly, there are instances where a code snipp ...

Having difficulty accessing POST data through $.ajax request

I am currently working on a simple JavaScript code that is set up to send POST requests to my local server. The JavaScript and PHP files are both located on localhost, so I don't have to worry about any cross-site issues for now. Here is the JavaScrip ...

What could be causing issues with my Ajax and JavaScript functionality?

While developing a website to search through my python database, I encountered an issue. The non-JavaScript version was functioning flawlessly. However, when attempting to implement AJAX so that the page would not have to be refreshed each time, I faced ...

Issue with saving cookie from Express.js backend to Nuxt.js frontend

After successfully creating an authorization server using Express.js, I encountered a problem when trying to save the access and rotating refresh tokens as signed cookies. The issue arose from having separate backend and frontend servers with different dom ...

Execute the jQuery function to submit the form via AJAX once the validation process has been

I am currently working on a form and implementing the jQuery validate plugin for validation purposes. My aim is to trigger the ajax code to submit the form only after the validation process is successfully completed. How can I achieve the following: // T ...

What might be causing the issue with my ajax request to the PHP file within the data parameter?

Although I am successfully getting my php value into a JavaScript variable, it seems like my script.js file is unable to find it. For the sake of brevity, some files have been omitted in this question. The main issue is that the script.js file retrieves th ...

Refreshing the Vuejs form is necessary for the router.push function to properly execute

Hey there! I've been working on a website that allows users to submit entries using a Laravel/Vuejs application. However, I've run into an issue where after filling out the form and submitting it, the loader gets stuck and the router.push doesn&a ...

Attempting to gather data from an HTML form and perform calculations on it using JavaScript

Looking for help with extracting user input from HTML and performing mathematical operations in JavaScript. Coming from a Python background, the variable system in JavaScript is confusing to me. Can someone provide guidance on how to achieve this? <div ...

Comparison of Vue 3 Composition API - watchEffect and watch

I've recently been delving into the world of Vue Composition API and have found myself pondering about the distinctions between watchEffect and watch. The documentation implies that watch functions similarly to the Vue 2 watch, leading me to speculate ...

A div containing a form, with the form being visually integrated within the div

Hi everyone, this is my first post here and I've tried to search extensively before asking this question. I've attempted to use the following examples without success: jquery submit form and then show results in an existing div Form submit ...

Tips for dynamically appending a string to a predefined variable in React

When I was working on creating a text input space using the input type area and utilizing the onChange utility, everything was running smoothly. Now, my task is to incorporate an emoji bar and insert a specific emoji into the input space upon clicking it. ...

Wavesurfer encounters difficulty generating waves due to a CROS Error caused by cookie settings

When using wavesurfer, an error occurs that states: XMLHttpRequest cannot load https://audiotemp.domain.net/RE65bbf6f0a2760184ab08b3fbf9f1d249.mp3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http ...

What is the process for pausing a video while it is still buffering and loading?

Is it possible to suspend a video when it is in an opening or preparing state? For example, if I open a video and then switch to another application using the smart hub feature, how can I suspend the video while it is in the process of opening or preparin ...

Updating the state after receiving API results asynchronously following a function call

I am attempting to update the state asynchronously when my fetchWeather function is executed from my WeatherProvider component, which calls an axios request to a weather API. The result of this request should be mapped to a forecast variable within the fet ...