Tips for storing unique values in an object using JavaScript

I need assistance with organizing my log data, which includes camera names and system IP addresses. I am trying to create an object where each unique system IP is a key, with an array of corresponding camera names as the value. Here is the code snippet I have been working on ---

    $http(req).success(function(data){
    $scope.logs = data;
    $scope.cameras={};
    var v =$scope.logs[0].systemIp;
    $scope.cameras["v"]=[];
    $scope.cameras["v"].push($scope.logs[0].cameraName);
    for(i=1;i<$scope.logs.length;i++){
        v=$scope.logs[i].systemIp;
        var flag=0;
        for(j in $scope.cameras){
            if(j==="v")
            {
                flag=1;
                break;
            }
        }
        if(flag==0)
        {
            $scope.cameras["j"]=[];
            $scope.cameras["j"].push($scope.logs[i].cameraName);
        }
        else if(flag==1)
        {
            $scope.cameras["v"].push($scope.logs[i].cameraName);
        }
    }});

This is a sample of my log data --

    [{
    "_id": "57683fd82c77bb5a1a49a2aa",
    "cameraIp": "192.16.0.9",
    "cameraName": "garage2",
    "systemIp": "192.168.0.2"
    },
    {
    "_id": "57683f8e2c77bb5a1a49a2a9",
    "cameraIp": "192.16.0.8",
    "cameraName": "garage1",
    "systemIp": "192.168.0.2"
    },
    {
    "_id": "57683f5e2c77bb5a1a49a2a8",
    "cameraIp": "192.16.0.7",
    "cameraName": "Back Door",
    "systemIp": "192.168.0.4"
    }]

When I check the console for $scope.cameras, it currently displays this output -

    Object { v: Array[3] }

I would like the cameras object to be structured like this --

    { "192.168.0.2" : [ "garage1" , "garage2"] ,
      "192.168.0.4" : [ "Back Door"] }

I'm new to javascript, so any guidance would be greatly appreciated.

Answer №1

If you opt to utilize the Lodash or Underscore library (which comes highly recommended), you can leverage the _.groupBy() function to achieve your desired outcome (while incorporating a few additional functions to ensure uniqueness across all values).

Nevertheless, you also have the option to create your own implementation easily:

function groupByDistinct(arr, prop, mapFn) {
    mapFn = mapFn || function (x) { return x; };
    var output = {};
    arr.forEach(function (item) {
        var key = item[prop],
            val = mapFn(item);
        if (!output[key]) {
            output[key] = [val];
            return;
        }
        if (output[key].indexOf(val) < 0) {
            output[key].push(val);
        }
    });
    return output;
}

Implement it in your code as shown below:

$scope.cameras = groupByDistinct(data, 'cameraIp', function (logEntry) { 
    return logEntry.cameraName;
});

Answer №2

When you pass a string like "v" or "j" as your object key, the string itself becomes the key instead of the intended value of these variables. To address this issue, consider using the following approach:

for(index = 0; index < $scope.logs.length; index++){
    var _sysIp = $scope.logs[index].systemIp,
        _camName = $scope.logs[index].cameraName;

    if(!$scope.cameras.hasOwnProperty(_sysIp)) {
        $scope.cameras[_sysIp] = [_camName];
    } else if ($scope.cameras[_sysIp].indexOf(_camName) < 0) {
        $scope.cameras[_sysIp].push(_camName);
    }

}

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

Javascript enables the magnetization of cursor movements

Can a web page be designed so that when users open it and hover their mouse over a specific area outside of an image, the mouse is attracted to the image as if by a magnet? Is this idea feasible? Any suggestions would be appreciated. ...

sanitizing user input in an AngularJS application

I created a feature in angular using ng-repeat <ul class="messages"> <li ng-repeat="e in enquiries"> <img src="/img/avatar.jpg" alt=""> <div> ...

Error: AngularJS has encountered an Uncaught ReferenceError stating that the controller is not defined within the

The code I am working with looks like this; var app = angular. module("myApp",[]). config(function($routeProvider, $locationProvider) { $routeProvider.when('/someplace', { templateUrl: 'somete ...

Issue with React-Toastify not displaying on the screen

After updating from React-Toastify version 7.0.3 to 9.0.3, I encountered an issue where notifications are not rendering at all. Here are the steps I followed: yarn add [email protected] Modified Notification file import React from "react" ...

What's the best method for efficiently hiding/showing a large number of DOM elements?

Imagine you have a maximum of 100 elements that remain consistent in type and format, but their content changes. These elements are connected to an input field and will update as the user types. What would be the most efficient approach for maximizing per ...

Retrieve JSON information from a document through JavaScript

Is it possible to fetch JSON data using JavaScript without relying on jQuery? I am only interested in retrieving data using pure JavaScript. Here is an example of my JSON file: {"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_d ...

What is the best way to retrieve dynamic content from a .txt file and have it displayed on multiple HTML pages as they are loaded dynamically?

I have a file named 'm_data.txt' stored on the server that contains a continuous total of 77 (for instance). The total gets updated via a push.php page that writes to the .txt file. <!DOCTYPE html> <html> <head> <title> ...

Struggling to find a solution for your operating system issue?

We are currently attempting to utilize the markdown-yaml-metadata-parser package for our project. You can find more information about the package here. Within the package, it imports 'os' using the following syntax: const os = require('os ...

Frontend update: Changing the display format for dates

Received from the backend is an array of objects (leavedays)- var leavedays = [{"_id":"62d544ae9f22d","season":2022,"name":"LEAVEDAY1","dateFrom":"2022- 07-26T00:00:00.000Z","date ...

Console log is not displaying the JSON output

I am currently working on implementing a notification button feature for inactive articles on my blog. I want to ensure that the admin does not have to reload the page to see any new submitted inactive articles. To achieve this, I am looking to use Ajax, a ...

How come attempting to read a nonexistent document from Firestore results in an uncaught promise?

I've been struggling to read and display data from Firestore, but I keep seeing error messages in the console. Encountered (in promise) a TypeError: Unable to read properties of undefined (reading 'ex') Encountered (in promise) a TypeError ...

Issue with Angular JS: ng-repeat not refreshing within ng-view

Whenever I make changes to the data stored in the variable $scope.userMovies, ng-repeat fails to update when it is inside an ng-view. Strangely enough, if it's placed outside of ng-view, everything updates as intended. What could be the reason behind ...

What is the process for uploading images in the backend of a Next.js API?

I am working with Next.js and an API. I need to be able to upload two files and include one text input field using the API backend. I have been struggling to find a solution for uploading files with different fields along with a single text input field in ...

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...

"Utilizing Promises in AngularJS Factories for Synchronous API Calls

Attempting to implement synchronous calls using a factory pattern. $scope.doLogin = function (username, password, rememberme) { appKeyService.makeCall().then(function (data) { // data = JSON.stringify(data); debugAlert("logi ...

What is the best way to check for date equality in Node.js?

I am dealing with this code condition: stopped_at: { $lte: new Date(Date.now() - 86400 * 1000) } The above code successfully retrieves dates that are less than or equal to 24 hours ago. However, I am wondering if there is a simpler solution a ...

Can you explain how the functionality of setState operates within React in this specific situation?

I've been working on updating the state of an object in my array. I managed to get it done, but I'm a bit confused about how it works. toggleVisited = countryCode => { var countries = [ ...this.state.countries ]; var countryToChange = c ...

Understanding the fundamentals of parseInt() and radix conceptsORExploring

Could you clarify the concept of radix in relation to parseInt()? I'm struggling to grasp how the string argument varies with different bases/radix. ...

Deciding whether an altered image has been successfully loaded

Currently, I am stuck on a minor point while creating a small gallery using jQuery. The code snippet looks like this: <script type="text/javascript> $(document).ready(function(){ $('#thumb1').click(function(){ $('#fullimage ...

Different ways to verify if a Checkbox is selected within a table

As a newcomer to reactjs, I have a component that renders two tables with different data using the same component and passing data through props. Each table has checkboxes for selection. If a user selects items from both tables, I want to detect if they ha ...