Filtering JSON data with JavaScript

Looking to group data in AngularJS using UnderscoreJS. Here is the JSON data:

 data = [   
        {
          "Building*": "Building A",
          "Wing*": "Wing C",
          "Floor*": "Floor 3",
          "Room Name*": "Room 3",
          "Room Type*": "AC",
          "Location*": "Location 1",
          "Device ID*": 27,
          "Category*": "Soap Hygene",
          "Dispenser Name*": "Dispenser 34",
          "Type*": "Manual",
          "Cartridge Type*": "Type 1",
          "Date of installation": "2016-04-11T06:06:22 -06:-30",
          "Contact Last Name": "Maynard",
          "Email Address": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47332f282a263469252834242f223507202a262e2b6924282a">[email protected]</a>",
          "Mobile Number with country code": "+1 (949) 590-3465",
          "Description": "Description of device",
          "Model": 37
        },
        {
          "Building*": "Building B",
          "Wing*": "Wing B",
          "Floor*": "Floor 3",
          "Room Name*": "Room 1",
          "Room Type*": "AC",
          "Location*": "Location 3",
          "Device ID*": 26,
          "Category*": "Soap Hygene",
          "Dispenser Name*": "Dispenser 33",
          "Type*": "Manual",
          "Cartridge Type*": "Type 2",
          "Date of installation": "2015-07-24T12:42:24 -06:-30",
          "Contact Last Name": "Holland",
          "Email Address": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42362a2d2f23316c202d31221a27300225">[email protected]</a>",
          "Mobile Number with country code": "+1 (947) 491-2353",
          "Description": "Description of device",
          "Model": 32
        }         
      ]

Desired format:

  updateData = [{ 
    building: 'Building A' , 
    buildingData:[{
        wing: "Wing A",
         wingData: [{
          floor:'Floor 2',
          floorData:[{
            room:'Room 3',
            roomData:[]
            }]
          }]
        }]
  }];

Tried implementing it on jsFiddle, but it didn't work. Seeking assistance. Thank you.

Answer №1

It seems like you are looking to group the data in a nested order as follows:

Building -> Wing -> Floor -> Room

To achieve this, you can utilize recursion or loop through the data by providing an array of the desired nesting order. Here is a sample code snippet for reference:

const nestedOrder = ['Building*', 'Wing*', 'Floor*', 'Room Name*']

function groupFilter (rawData, attrList) {
  if (attrList.length == 0) return rawData

  var currentAttr = _(attrList).first()
  return _(rawData)
    .chain()
    .groupBy(currentAttr)
    .map((list, attrName) => Object({
      [currentAttr]: attrName,
      [`${currentAttr}Data`]: groupFilter(list, _(attrList).rest())
    }))
    .value()
}

console.log(groupFilter(data, nestedOrder))

This approach will condense the raw data to the innermost attribute specified, which in this case is 'Room Name*'. You can then apply your custom filter logic to determine the contents of RoomData.

If performance is not a major concern, this method should work effectively for your needs.

I hope this solution is helpful and meets your requirements.

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

Making changes to a JSON file using JavaScript

Hello everyone, I am a beginner in Javascript and have successfully created a system that allows me to search and filter users in my data.json file. However, I am now looking to develop an application that can add users to the data.json file. Any advice or ...

Looking to add some random circle markers to your SVG map?

I currently have a single marker displayed on an SVG Map. My goal is to scatter markers randomly across the map within the path itself. I would greatly appreciate some assistance in implementing this feature. svg { border: 1px solid; overflow: visib ...

Creating "search result pages" with HTML, PHP, Javascript, and MySQL

Consider the scenario where you have a table with two columns: id and name, containing thousands of rows. You have a search engine that allows searching by free text, using the query: SELECT * FROM `table` WHERE `name` LIKE '%$search%' The res ...

Reconfigure a portion of a string using Vue's dynamic replacement feature

Currently tackling a problem. In my possession is a string that essentially consists of HTML code: let htmlTitle = "<a href="/news/sky-sport-hd-in-italia-dal-18-novembr">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-g ...

Choose a specific element using jQuery based on a class that is shared by several elements

I am looking to target an element with the class 'submenu-expand' and apply an additional class to it. $('.menu-item').on('click',function(){ $('.submenu-expand').toggleClass('expanded') }) While this cod ...

React/NextJS: Firebase Realtime Database displaying the message "Error: Client is offline"

Encountering an occasional error when using React with NextJS to fetch data from a Firebase Realtime Database. Unhandled Runtime Error Error: Error: Client is offline. Currently utilizing Firebase version 9.0.1 for React. The initialisation and configura ...

Utilize datetime values in chartjs ajax for data visualization

I'm currently working on creating a chart using chart.js. I have php code that retrieves datetime data through an ajax call. However, the chart is not displaying any data and there are no visible errors. I've checked the php code using console.lo ...

Is it possible to trigger an AJAX validation only after the jQuery validation plugin has successfully validated the input?

I utilized the jQuery validation plugin for form field validation. The goal now is to send an ajax request only when the fields are deemed valid by the jQuery validation plugin. JavaScript: $(function(){ $("#form").validate({ errorPlacement: ...

Synchronize information between two drop-down lists

I am currently utilizing the boostrap library to create a pair of dropdown lists. My goal is to have the items in the second dropdown list dynamically update based on the selection made in the first dropdown. Within my code, there exists a dictionary name ...

Using v-for to show the values of an object in Vuetify

I am currently developing a function in vuejs that allows users to select tables from a database, with the columns' names automatically appearing in a v-list-item component. However, I am facing difficulty in displaying these column names effectively. ...

Tips for updating a boolean value in a JSON file with a button in Angular and TypeScript

Can someone guide me on how to create a function in my table-viewer.component.ts file that can update the status from "false" to "true" in a JSON file when a user clicks the cancel button? The JSON file has the following information. db.json "firstN ...

Unable to retrieve scope data in controller function

Having trouble accessing the scope attribute fullName from the controller method login. What could be causing this issue? App.controller('LoginController', ['$scope', 'LoginService', '$location', function(scope, Log ...

Guide to activating animation on one element when hovering over another element?

I am setting up an HTML 5 range element and looking to enhance the user experience. Specifically, I want to implement a feature where when the user hovers over the range, the height and width of the thumb should increase to 12 pixels. CSS .myrange::-webk ...

transferring information from PHP to JavaScript through the use of JSON encoding

I am currently in the process of developing a Google maps page that utilizes latitude and longitude data coordinates to generate a heat map displaying the distribution of foxes within a specific area. At present, my application functions properly when the ...

Get your hands on the base64 image by triggering the save as popup and downloading

I am facing a challenge with downloading a base64 image onto the user's machine. So far, I have attempted the following steps: var url = base64Image.replace(/^data:image\/[^;]+/, 'data:application/octet-stream'); window.open(url); an ...

React App stalled due to continuously running function

In this section of my React app, the createBubbles function is functioning properly. However, I am encountering an issue where the entire app freezes when navigating to another page after visiting this one. The console displays the following errors and de ...

Accessing the statusText of a 403 response in Axios (React, Express, Node.js)

Within my component, there is a register function that makes an API call. The API checks if the email already exists and provides an appropriate status and statusText based on the result. Below is the API call handler in my Express app: router.post(' ...

The $route object in Vue is not configured

Currently, I am delving into the realm of Vue router and aiming to achieve programmatic navigation without relying on <router-link> in my templates file. Here is a glimpse of my router and view setup: router = new VueRouter({ routes: [ ...

Determine total and showcase it as the range slider is adjusted

Seeking to calculate and present the result of three range sliders. The equation I aim to showcase is: KM driven per year * Avg KM/100L / Price of fuel I have managed to display each slider's individual values, but I am uncertain about how to show t ...

The absence of PHP GET variable being set

I am encountering an issue with my registration php class. It is designed to display a form and upon clicking the registration button, it triggers a function in a login javascript file. This JavaScript file utilizes ajax to send data to an index.php file. ...