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

Mobile version experiencing issue with Navbar not collapsing

The dropdown navigation bar on the mobile version of my website is not functioning properly. Despite several attempts, I have been unable to figure out a way to make it work effectively. <!DOCTYPE html> <html lang="en"> <head> & ...

Intercepting HTTP requests on specific routes with Angular 4+ using an HTTP Interceptor

I've developed an HTTP_INTERCEPTOR that needs to function on certain routes while excluding others. Initially, it was included in the main app module file. However, after removing it from there and adding it to specific modules, the interceptor conti ...

What is the method to individually determine "true" or "false" using .map() in coding

I am faced with an array of data that needs to be manipulated individually, but it should still function as a cohesive unit. Can you assist me in achieving this? function OrganizeFollow() { const [followStatus, setFollowStatus] = useState([]); co ...

How to modify the color of the placeholder text in a select dropdown using Material-ui

I have a material-ui select component that displays a dropdown menu of options for the user to choose from. The placeholder text, which currently reads "select option," appears in light grey to prompt the user to make a selection. However, I am concerned t ...

Using Node.js to send a response only after every promise has been resolved

I am currently working on a NodeJS Express route where I have encountered an issue. In this route, a function is called multiple times, each returning a Promise. The values from these Promises are then added to an Array and sent back to the client using re ...

Utilize the power of jQuery's AJAX capabilities

Is it normal for a jQuery AJAX request to take between 1-2 seconds before receiving a response? Is there any way to minimize this delay? The response type is JSON and the HTML code is small. Thank you! ...

Why is MutationRecord[] organized as an array in MutationObserver?

I've been diving into the world of MutationObserve, and I've grasped most of it. However, one thing that's puzzling me is why the parameter requires an array. According to the documentation: An array of MutationRecord objects, detailing e ...

Mastering the Art of jQuery: Easily Choosing and Concealing a Div Element

I'm currently facing challenges in removing a div upon successful AJAX completion. The issue I'm encountering is that the word "Added" appears twice after success, indicating that I am not properly selecting the two divs containing it. Any sugges ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

"Internet Explorer text input detecting a keyboard event triggered by the user typing in a

It appears that the onkeyup event is not triggered in IE8/IE9 (uncertain about 10) when the enter button is pressed in an input box, if a button element is present on the page. <html> <head> <script> function onku(id, e) { var keyC = ...

Bootstrapvalidator does not function properly with select2.js

My code is not validating the select field. What could be causing this issue? Can anyone provide a solution? Apologies for my poor English, and thank you in advance for your response. Here is my form: <form name="form_tambah" class="form_tambah"> ...

What is a way to automatically run a function at specific intervals in PHP, similar to the setTimeout() function in JavaScript?

I have a JavaScript code snippet that looks like this: setTimeout('$.ajaxCall("notification.update", "", "GET");', 1000); Now, I want to execute the following PHP function every 1000 milliseconds, similar to the above JavaScript code: $notific ...

Angular 4 after ejection, coupled with automated end-to-end testing using Protractor/Selenium setup

I am attempting to conduct end-to-end tests using Protractor/Selenium on an Angular 4 project that has been ejected. Here is my package.json: ... "scripts": { "pree2e": "webdriver-manager update --standalone false --gecko false --quiet node", "e2 ...

What is the best way to access a resource from an Angular.js module for a jasmine test?

My current project module includes resources and the code is structured as follows: editor_services.js var editorServices = angular.module('editorServices', ['ngResource']); editorServices.factory('Project', ['$resource ...

Ways to retrieve data from an AJAX success callback function

Within my front end JavaScript application, I need to execute an ajax request in order to retrieve data from the server. Once this data is acquired, I aim to display it within the view. var retrievedData; $.ajax({ url:"/getDataFromServer.json", ty ...

Identify the moment a dialogue box appears using jQuery

I'm facing a situation where multiple dialogs are opened in a similar manner: $("#dialog").load(URL); $("#dialog").dialog( attributes, here, close: function(e,u) { cleanup } The chall ...

I need help figuring out how to navigate between different pages in my Vue-cli app that has multiple pages configured

After following the guide on https://cli.vuejs.org/config/#pages, I successfully configured vue-cli3 to build a multiple page application. My project consists of 2 static pages, and I set up the vue.config.js file as shown below. However, when running the ...

How can I remove a quadratic curved arrow tool in Fabric JS canvas after it has been created?

I'm currently working on developing a tool for creating quadratic curved arrows. For reference, I utilized a demo from the following link to build the tool: I have successfully created the tool as per my requirements. However, I am encountering some ...

Swapping out the JSON data from the API with HTML content within the Vue.js application

I am currently working on a project involving Vite+Vue.js where I need to import data from a headless-cms Wordpress using REST API and JSON. The goal is to display the titles and content of the posts, including images when they appear. However, I have enco ...

Unlocking the Power of Combining JMVC and Server-side MVC Models

It's been a few days since I posted this question here and still no response. I also tried posting it on forum.javascriptMVC.com and finally got an answer, but I'm looking for more insights. Here's my question: After reading the documentat ...