Streamline JSON arrays into separate variables based on their respective categories

Received a JSON output from a PHP file with the following structure;

[{"device_id":"9700001","sensor_value":"31.5","update_time":"2017-04-28 18:49:06"},
{"device_id":"9700002","sensor_value":"31.5","update_time":"2017-04-28 18:47:05"},
{"device_id":"9700003","sensor_value":"31.5","update_time":"2017-04-28 18:45:05"},
{"device_id":"9700003","sensor_value":"33.1","update_time":"2017-04-28 06:24:57"},
{"device_id":"9700002","sensor_value":"33.1","update_time":"2017-04-28 06:22:57"},
{"device_id":"9700003","sensor_value":"33.1","update_time":"2017-04-28 06:20:56"},
{"device_id":"9700001","sensor_value":"33.1","update_time":"2017-04-28 06:18:56"},
{"device_id":"9700002","sensor_value":"33.1","update_time":"2017-04-28 06:16:56"},
{"device_id":"9700002","sensor_value":"33.1","update_time":"2017-04-28 06:14:56"}]

The task is to convert this array into specific datasets by extracting values of device 9700001 and its corresponding update time along with sensor value, creating two separate datasets as shown below,

datasensor1=[{"sensor_value":"31.5","update_time":"2017-04-28 18:49:06"},{"sensor_value":"33.1","update_time":"2017-04-28 06:18:56"},{"sensor_value":"33.1","update_time":"2017-04-28 06:18:56"}]

For device 9700002,

 datasensor2=[{"sensor_value":"31.5","update_time":"2017-04-28 18:47:05"},{"sensor_value":"33.1","update_time":"2017-04-28 06:22:57"},{"sensor_value":"33.1","update_time":"2017-04-28 06:16:56"},{"sensor_value":"33.1","update_time":"2017-04-28 06:14:56"}]

Following a similar pattern for device 9700003,

 datasensor3=[{"sensor_value":"31.5","update_time":"2017-04-28 18:45:05"},{"9700003","sensor_value":"33.1","update_time":"2017-04-28 06:24:57"},{"sensor_value":"33.1","update_time":"2017-04-28 06:20:56"}]

Attempted to group the data by device_id using

 var sensor= _.groupBy(data,"device_id"); 

However, encountering difficulty in separating the objects afterward. Seeking advice on how to resolve this issue?

Answer №1

Implementing filter() and map():

var info = [{"device_id":"9700001","sensor_value":"31.5","update_time":"2017-04-28 18:49:06"},
{"device_id":"9700002","sensor_value":"31.5","update_time":"2017-04-28 18:47:05"},
{"device_id":"9700003","sensor_value":"31.5","update_time":"2017-04-28 18:45:05"},
{"device_id":"9700003","sensor_value":"33.1","update_time":"2017-04-28 06:24:57"},
{"device_id":"9700002","sensor_value":"33.1","update_time":"2017-04-28 06:22:57"},
{"device_id":"9700003","sensor_value":"33.1","update_time":"2017-04-28 06:20:56"},
{"device_id":"9700001","sensor_value":"33.1","update_time":"2017-04-28 06:18:56"},
{"device_id":"9700002","sensor_value":"33.1","update_time":"2017-04-28 06:16:56"},
{"device_id":"9700002","sensor_value":"33.1","update_time":"2017-04-28 06:14:56"}];

var organized = {};
info.forEach((item) => {
organized[item.device_id] = [];
});
Object.keys(organized).forEach((id) => {
  organized[id] = info.filter((row) => row.device_id === id).map((row) => ({
    sensor_value: row.sensor_value,
    update_time: row.update_time
  }));
});

console.log(organized);

Answer №2

Check out the Array#reduce function

var data =[{"device_id":"9700001","sensor_value":"31.5","update_time":"2017-04-28 18:49:06"},
{"device_id":"9700002","sensor_value":"31.5","update_time":"2017-04-28 18:47:05"},
{"device_id":"9700003","sensor_value":"31.5","update_time":"2017-04-28 18:45:05"},
{"device_id":"9700003","sensor_value":"33.1","update_time":"2017-04-28 06:24:57"},
{"device_id":"9700002","sensor_value":"33.1","update_time":"2017-04-28 06:22:57"},
{"device_id":"9700003","sensor_value":"33.1","update_time":"2017-04-28 06:20:56"},
{"device_id":"9700001","sensor_value":"33.1","update_time":"2017-04-28 06:18:56"},
{"device_id":"9700002","sensor_value":"33.1","update_time":"2017-04-28 06:16:56"},
{"device_id":"9700002","sensor_value":"33.1","update_time":"2017-04-28 06:14:56"}]

function group(data , id){
return data.reduce((a,b)=>{
if(b.device_id == id)
a.push({
sensor_value:b.sensor_value,
update_time:b.update_time
})
return a
},[])
}
console.log(group(data,9700001))
console.log(group(data,9700002))

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

The issue with applying local css links in Bootstrap 3 is not being resolved

I am currently in the process of developing a flat website for my landlord using the Bootstrap 3 framework. However, I'm facing an issue where my navigation bar is only displaying as an unordered list rather than a horizontal bar. The CSS code can be ...

Is it feasible to maintain a variable as a reference across views while utilizing ng-view?

I am facing a unique challenge: I have a webpage with two tabs that need to utilize ng-view from AngularJS. The twist is that both tabs must share the same variable, similar to referencing a variable in C# using the "ref" keyword. If you want to see an ex ...

Can express middleware be tailored for each individual handler within the same route path?

I am seeking to create distinct routes under an /api path with varying middleware handlers, each allowing for different authentication methods. My initial approach was to nest these API routes under separate instances of the Router object using Express: c ...

Guide to storing user id in a session array using CodeIgniter

Hello all, I'm relatively new to Codeigniter and could use some guidance. If anyone can provide assistance by posting the answer here, I would greatly appreciate it. Thank you in advance. Below is my Controller: public function login() { $this- ...

Issue with modal not being able to close the embedded video iframe

I have created a demo of a video in my footer that uses external CSS files and works perfectly. However, when I added it to the project, everything works except for closing the video. After clicking the play button in the footer, a modal appears on the sc ...

Traverse an array in JavaScript using jQuery, PHP, and AJAX

Trying to iterate through a JavaScript object using AJAX has led me to explore options like json_decode, but it turns out this is an array and not an object. var array = [{type: 'a', value: 1}, {type: 'b', value: 1}] $.ajax{ url: "p ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

What is the method for obtaining an element with a class name that does not match a specific value?

I'm trying to figure out how to select an element with a class name that is different from the value passed in. For example: $(document).ready(function () { $(document).on('change', '#allRolesDD', function () { var toS ...

Troubleshooting: Issues with Integrating Javascript and CSS into

I'm still new to this platform, so please correct me if I make any mistakes. My goal is to create a "task table" that allows users to edit existing tasks and add new ones. Thanks to the base template provided by Ash Blue, I've managed to program ...

Concentrate and select non-interactive elements with your mouse

Is it possible to set tab index on non-form elements like the div tag? I tried using tab index, but when the div is focused and the enter button is tapped, the ng-click event associated with the div tag is not triggered. <div tabindex="0" role="butto ...

How can we extract validation data from a function using Ajax and then transfer that information to another Ajax query?

I have an AJAX function that validates a textbox on my page. After validating, I need to perform an action with that value (search in the database and display results in the textbox). However, I also need the validation function for another separate functi ...

The presence of ng-show dynamically adjusts the minimum height of a div element

I am encountering an issue with a div that has the class of wrapper. Inside this div, there is a parent div with the class of content-wrapper. The wrapper div includes a conditional directive ng-show which toggles between displaying or hiding its content. ...

Pass information from an array of objects to a visual component

My objective is to display 3 instances of the SearchItem component from locations[0].results[0] and 3 instances from locations[0].results[1] I have an array containing objects with data that I want to display in my SearchItem component: const locations = ...

Combining multiple arrays into a single array using functions and pointers in the C programming language

I have attempted using functions and arrays to solve this problem, but I have encountered difficulties and now want to tackle it using pointers. However, I am facing issues with passing and accessing array values using pointers. Below is the code snippet ...

Gulp: executing a task with no specified output location

I am attempting to create a straightforward task to display the file size for each file in an array of paths using the gulp-size plugin, as shown below: var gulp = require('gulp') var size = require('gulp-size') gulp.task('size&a ...

How to position items at specific coordinates in a dropdown using JavaScript

I have five images in my code and I would like to arrange them in a circular pattern when they are dropped into the designated area. For example, instead of lining up the five images in a straight line, I want them to form a circle shape once dropped. Ho ...

com.sun.istack.SAXException2: The context does not recognize class java.util.LinkedHashMap or any class in its inheritance hierarchy

A POST request is being sent to create a resource named ContentInstance. Resource: ContentInstance. // This code snippet was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 import java.math.BigInteger; impo ...

Mapping the correct syntax to apply font styles from an object map to the map() function

React, JS, and Material UI Hey there, I have a question about my syntax within the style property of my map function. Am I missing something? Fonts.jsx export const fonts = [ { fontName: 'Abril', key: 'abril', fontFamily ...

Backbone - First render client views before creating them upon saving

I'm completely stumped on how to make this work. I can successfully create the models, but running create or anything else on them afterwards seems impossible. It's been 6 long hours of trying and failing... Can someone please point out where I&a ...

Tips for properly including my Dialog Flow access token in the environment file within the Angular CLI

I am currently in the process of creating a bot using angular cli and integrating dialog flow's API. The issue I am facing is that when I perform debugging in Chrome, I encounter the following error logs: ApiAiClientConfigurationError columnNumber: ...