Iterate through the elements within the object using a dotted name and selectively extract items based on the specified attribute

In my script, there is a global variable named "ccu-192_168_30_22" which holds the following data:

{
    "values": {
        "VirtualDevices.INT0000001:1.CONTROL_MODE": {
            "topic": "",
            "payload": 0,
            "deviceName": "F2-1315.03",
            "datapoint": "CONTROL_MODE",
            "room": "F2"
        },
        "HmIP-RF.00201BE9A13271:1.CONTROL_MODE": {
            "topic": "",
            "payload": 0,
            "deviceName": "F02A-1315.02",
            "datapoint": "CONTROL_MODE",
            "room": "F02A"
        },
        "HmIP-RF.00265BE98E8C53:0.UNREACH": {
            "topic": "",
            "payload": 0,
            "deviceName": "F1-1315.01",
            "datapoint": "UNREACH",
            "room": ""
        }
    }
}

I am trying to extract device names and rooms from objects with "datapoint": "CONTROL_MODE", using the code snippet provided below.

for (var device in global.get("ccu-192_168_30_22").values) {
if (device.datapoint == "CONTROL_MODE") {
    list.push(device.deviceName);
    list.push(device.room);
    }
}
msg.payload = list;
return msg;

However, when I run this code, I only receive an empty array as msg.payload.

Answer №1

To achieve the desired outcome, utilize both a filter and a map function.

In order to properly format your object, I found it necessary to include some commas.

const data = {
    "values": {
        "VirtualDevices.INT0000001:1.CONTROL_MODE": {
            "topic": "",
            "payload": 0,
            "deviceName": "F2-1315.03",
            "datapoint": "CONTROL_MODE",
            "room": "F2"
        },
        "HmIP-RF.00201BE9A13271:1.CONTROL_MODE": {
            "topic": "",
            "payload": 0,
            "deviceName": "F02A-1315.02",
            "datapoint": "CONTROL_MODE",
            "room": "F02A"
        },
        "HmIP-RF.00265BE98E8C53:0.UNREACH": {
            "topic": "",
            "payload": 0,
            "deviceName": "F1-1315.01",
            "datapoint": "UNREACH",
            "room": ""
        }
    }
}
const obj = Object.values(data.values)
  .filter(({datapoint}) => datapoint === "CONTROL_MODE")
  .map(({deviceName,room}) => ({deviceName,room}))
console.log(obj)

Answer №2

If you want to simplify it, consider the following format:

{
   "VirtualDevices.INT0000001:1.CONTROL_MODE":{
      "topic":"",
      "payload":0,
      "deviceName":"F2-1315.03",
      "datapoint":"CONTROL_MODE",
      "room":"F2"
   },
   "HmIP-RF.00201BE9A13271:1.CONTROL_MODE":{
      "topic":"",
      "payload":0,
      "deviceName":"F02A-1315.02",
      "datapoint":"CONTROL_MODE",
      "room":"F02A"
   },
   "HmIP-RF.00265BE98E8C53:0.UNREACH":{
      "topic":"",
      "payload":0,
      "deviceName":"F1-1315.01",
      "datapoint":"UNREACH",
      "room":""
   }
}

To simplify further, use this code snippet:

Object.values(your_data).filter(item => item.datapoint === "CONTROL_MODE");

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

Transmit information via AJAX using the React Flux design pattern

Here is my React code snippet: var AddRecord = React.createClass({ getInitialState: function() { return { Data: [] } }, sendData : ...

NextJS 12: The dilemma of styled components not rendering server side due to missing CSS

Exciting news with the latest NextJS 12 release - now styled-components is supported without the need for any extra plugins on NextJS! However, I'm running into issues getting it to work with server-side rendering. To activate it, I installed the sty ...

Running the npm install command will eliminate any external JS or CSS files that are being

For my project, I incorporated jquery-datatimepicker by including jquery.datetimepicker.min.css and jquery.datetimepicker.full.min.js in angular.json and placed them within the node_modules/datetimepick directory. Here is a snippet of my angular.json conf ...

Emphasize a checkbox by selecting it when another checkbox is checked

I have a question about checkboxes and highlighting the checkmarks. The issue I am facing is that I have multiple checkboxes with the same ID for different screen resolutions. When I click on the label for "Check 1" it highlights the corresponding checkmar ...

Encountering issue with express 4.x bodyparser functionality

I recently updated my body-parser to the latest version (1.17.1) and made sure to organize my code as advised by others. import express import body-parser app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended : fa ...

Using a Material-UI component to activate a React Router Link

Currently, I am facing an issue while using material-ui components in react with react-router. The problem arises when I try to display list-items that double up as link elements but also have a submenu inside which should not activate the parent link. Unf ...

Django REST Framework: Converting Data to JSON and Fetching it Using JavaScript from my API

How can I retrieve data from my API using JavaScript? My objective is to present my model data in the form of charts or graphs. For the visualization part, I have chosen Charts.js. Currently, I am able to display a chart in my template with default data. ...

Provide a numerical representation of how frequently one object value is found within another object value

Account Object Example in the Accounts Array: const accounts = [ { id: "5f446f2ecfaf0310387c9603", picture: "https://api.adorable.io/avatars/75/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6b7d7a666 ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

Retrieving query filters and URL parameters using PHP

I am in the process of developing a new advertising website. My main focus is on creating a search page that will feature various filters such as: <h2>Make</h2> <a href="index.php?page=search&make=renault">Renault</a> <a hr ...

Decoding JSON data using Gson

Here is some JSON data I am working with: { "boards": [ { "board": "3", "title": "3DCG", "ws_board": 1, "per_page": 15, "pages": 11 }, { "board": "a", "title": "Anime & Manga", ...

jQuery can help in determining the cost based on chosen preferences

Here is my unique html code : <select class="form-control B3 pricing" name="B3"> <option data-price="0" data-cheap="0">0</option> <option data-price="20" data-cheap="30">1</option> <option data-price="40" data-cheap ...

Reveal the array on the frontend in a row each time using Javascript

My array contains the following items: let array=["First", "Second"] I want to display each item on a separate line (without commas), like this: First Second I attempted splitting the array using: let data.split("\n") However, the output was: ...

Issues with updating table data when clicking the "Remove Selected" button a second time in Angular 8

Whenever I click the "Remove Selected" button on my table, the selected rows with checkboxes should be deleted. The issue is that it works perfectly fine the first time I click the button, but if I repeat the same steps (click the checkboxes and then click ...

Transmit JSON data from the client to the MarkLogic Server device

Hello everyone, hope you are all doing well. I am a beginner in Marklogic and recently managed to set up a rest api on my local machine. Following the given example, I used curl to send/create documents in the database. Now, my query is how can I access/ ...

Enhancing user experience by implementing AJAX in a contact form to eliminate the need for page

I have read numerous questions on this topic and have compiled the code I currently have from various responses. Unfortunately, despite my efforts, I am unable to make it work and I cannot identify the reason behind this issue. Below is the HTML form str ...

Incorporating a JavaScript script into my Angular 7 project

My project requires me to incorporate the "Loadingbar.js" library into one of my pages. You can find this library here: . Initially, I inserted the CSS code into my global "style.css" file. I started by placing the script in my index.html file: <script ...

Is there a way to prevent the imported JQuery from causing issues with current code implementations?

Being a novice developer in Html/Javascript/CSS/Jquery coding, I recently encountered an issue while integrating Jquery into my project. When I imported Jquery, the styling of simple buttons went haywire. Jquery worked perfectly fine when using its classes ...

Loop through and store data in Node.JS within an array

Initially, I attempted to use a simple for loop to iterate through the data. However, this approach didn't work due to the nature of request.save being a function. After some experimentation, I decided to utilize forEach instead. Everything seemed to ...

Adjust image size as the page is resized

My challenge is to resize images that are typically too large for the current window size, ensuring they fit within 85% of the client window. I tried creating a function utilizing onload and onresize events but encountered issues. function adjustImages(){ ...