Converting JSON values to JSON keys with AngularJS

var demoApp = angular.module('myApp', []);
demoApp.controller('MyController', function($scope, $http) {
    $scope.formData = {};
    $scope.formData.selectedTechnologies = {};

    $scope.checkSelected = function(object) {
        return Object.keys(object).some(function(key) {
            return object[key];
        });
    };

    $scope.technologies = [
      {id:1, name:'Angular JS'},
      {id:2, name:'PHP'},
      {id:3, name:'HTML'},
      {id:4, name:'JAVA'},
      {id:5, name:'CSS'},
      {id:6, name:'DOTNET'}
    ];
    
    //$scope.formData.selectedTechnologies = {'Angular JS':true, 'HTML':true}; /* This is working fine */
    
    var myTech = {"myTechnology":["Angular JS","HTML"]}; /* This is dynamic  value */
    $scope.formData.selectedTechnologies = myTech.myTechnology;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<body ng-app="myApp">
<h2>Technologies</h2>
<div ng-controller="MyController">
<form name="projectForm" novalidate ng-submit="projectForm.$valid && submitForm()">
<div class="col-sm-3" ng-repeat="technology in technologies">
<div class="checkbox checkbox-info checkbox-inline">
<input type="checkbox" name="technology_name" ng-model="formData.selectedTechnologies[technology.name]" id="technology{{$index}}" ng-required="!checkSelected(formData.selectedTechnologies)" />
<label for="technology{{$index}}" ng-bind="technology.name"></label>
<div class="col-lg-12" ng-show="projectForm.$submitted || projectForm.technology_name.$touched">
   <span ng-show="projectForm.technology_name.$error.required" class="text-danger">Select any technology.</span>
</div>
</div>
</div>
</form>
</div>
</body>

I have displayed a list of my current technologies. I need to automatically select Angular JS and HTML from my variable myTech.

When I set

$scope.formData.selectedTechnologies = {'Angular JS':true, 'HTML':true};
it works correctly.

Can anyone advise me on how to convert ["Angular JS","HTML"] to {"Angular JS":true,"HTML":true}?

Answer №1

No conversion necessary for your JSON object

var myTech = {
    "myTechnology": ["Angular JS", "HTML"]
  };

Simply update $scope.checkSelected

to the following

$scope.checkSelected = function(object) {
        return $scope.formData.selectedTechnologies.includes(object.name);
    };

and modify your html like this

<input type="checkbox" name="technology_name" ng-model="formData.selectedTechnologies[technology.name]" id="technology{{$index}}" ng-checked="checkSelected(technology)" />

ECMAScript 2016 now has an include method for arrays

TRY IT OUT ON FIDDLE

UPDATE : using indexOf as suggested by @tanmay in comments

$scope.checkSelected = function(object) {
        return $scope.formData.selectedTechnologies.indexOf(object.name) != -1;
    };

Answer №2

To generate such an array, you can utilize the elegant function known as reduce.

Here is an example:

$scope.formData
  .selectedTechnologies = myTech.myTechnology.reduce(function(arr, tech) {
    arr[tech] = true;
    return arr;
  }, []);

Below is a functional code snippet:

var demoApp = angular.module('myApp', []);
demoApp.controller('MyController', function($scope, $http) {
  $scope.formData = {};
  $scope.formData.selectedTechnologies = {};
  $scope.technologies = [{
      id: 1,
      name: 'Angular JS'
    },
    {
      id: 2,
      name: 'PHP'
    },
    {
      id: 3,
      name: 'HTML'
    },
    {
      id: 4,
      name: 'JAVA'
    },
    {
      id: 5,
      name: 'CSS'
    },
    {
      id: 6,
      name: 'DOTNET'
    }
  ]

  var myTech = {
    "myTechnology": ["Angular JS", "HTML"]
  };
  $scope.formData
  .selectedTechnologies = myTech.myTechnology.reduce(function(arr, tech) {
    arr[tech] = true;
    return arr;
  }, []);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<body ng-app="myApp">
  <h2>Technologies</h2>
  <div ng-controller="MyController">
    <div class="col-sm-3" ng-repeat="technology in technologies">
      <div class="checkbox checkbox-info checkbox-inline">
        <input type="checkbox" name="technology_name" ng-model="formData.selectedTechnologies[technology.name]" id="technology{{$index}}" ng-required="!checkSelected(formData.selectedTechnologies)" />
        <label for="technology{{$index}}" ng-bind="technology.name"></label>
      </div>
    </div>
  </div>
</body>

Answer №3

convert the given array to an object with key-value pairs using the map function.

var exampleApp = angular.module('myApp', []);
exampleApp.controller('MyController', function($scope, $http) {
    $scope.formData = {};
    $scope.formData.selectedTechnologies = {};
    $scope.technologies = [
      {id:1, name:'Angular JS'},
      {id:2, name:'PHP'},
      {id:3, name:'HTML'},
      {id:4, name:'JAVA'},
      {id:5, name:'CSS'},
      {id:6, name:'DOTNET'}
    ]
    
    var myTech = {"myTechnology":["Angular JS","HTML"]};
    var defaultTechnologies ={}
    defaultTechnologies = Object.assign(...myTech.myTechnology.map(d => ({[d]:true})))
    $scope.formData.selectedTechnologies = defaultTechnologies;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<body ng-app="myApp">
<h2>Technologies</h2>
<div ng-controller="MyController">
<div class="col-sm-3" ng-repeat="technology in technologies">
<div class="checkbox checkbox-info checkbox-inline">
<input type="checkbox" name="technology_name" ng-model="formData.selectedTechnologies[technology.name]" id="technology{{$index}}" ng-required="!checkSelected(formData.selectedTechnologies)" />
<label for="technology{{$index}}" ng-bind="technology.name"></label>
</div>
</div>
</div>
</body>

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

Using Backbone.sync to customize dataType

I am working on an application that utilizes a .CSV file as the primary data source for a Backbone Model. I am interested in finding the most effective approach to changing the sync method so that it uses dataType "text" instead of "json". Any insights on ...

Integration of C++ Applications: Comparing RabbitMQ and NodeJS Addon

I'm looking to interface with my C++ application using a NodeJS server. My main concern is whether there will be a significant decrease in performance when transmitting data between the C++ binary and the NodeJS server via RabbitMQ. For example, let& ...

The functionality of socketio can only be activated within a function by utilizing the window.alert

I encountered a strange issue while working on my web development project using Flask and vanilla JavaScript. I'm attempting to create a basic chat feature with socketio. Strangely, the functionality only seems to work when I include a window.alert in ...

Tips for transferring information from a React template to a Flask API

I am exploring the use of a sign-in template, but I'm uncertain about how to send data from this template to my Flask API. I have come across information suggesting that states are only used in components. Is this factual? I attempted to call the Regi ...

Guide on inserting random numbers into an array and calculating their total with ReactJs

My issue lies with a random number generator method that produces random numbers between 1 and 6. I have been adding these numbers to an array one by one, but the problem is that only the current value gets pushed into the array each time, not the previous ...

Storing Dark Mode Preference in Local Storage using JavaScript

I recently implemented dark mode on my website and it's working flawlessly. However, every time I refresh the page, it reverts back to the default Day Mode view. Is there a way to save these preferences? In the HTML section: <body> &l ...

Implementing a CSS stylesheet that is triggered when the user reaches the top of the webpage, and incorporating an

Currently, I have code that controls the hiding and showing of my navigation menu when a user scrolls up on the page. $.fn.moveIt = function(){ var $window = $(window); var instances = []; $(this).each(function(){ instances.push(new moveItItem($( ...

A JavaScript JSON request that includes several specific parameters

Here's a simple question: JavaScript needs to make a request to the server using this URL: myserver/scipt.php?LANG=EN&AGENT={"Login":{"name":"user","pass":"user"}} How should I structure the URL and data for an Ajax call? Is this approach co ...

Deactivate or Conceal certain ng-options within angularjs

I am facing an issue with my dropdown box. I want to add an input box once an option is selected, but then disable/hide/remove that option once the input box is added. And then enable the option again once the input box is removed. Is using the disabled ex ...

Tips for programmatically setting an option as the chosen selection?

Here is the structure of my HTML code: <select class="form-control" name="settings.provider" id="settings.provider" ng-model="settings.provider" required> <option value="" disabled selected>Select Provider</option> &l ...

Ensure that you do not repeat the same action

In my application built on Node.js, I am utilizing Express for API routes and MongoDB as the database. One of the functionalities includes a raffle where users should only be able to enter once. Currently, I am storing participant information in an arra ...

I am looking to grasp the concept of the Conditional ternary statement

I attempted to convert the code below into a ternary operator, but unfortunately ended up with an undefined result. Could someone please clarify where I made a mistake and advise on how to correct it properly? Thanks in advance. const plantNeedsWater = f ...

Leveraging nsIFilePicker.modeGetFolder in addon sdk

My extension creates a Panel that displays the currently selected preferences for the extension. I want to populate the Panel with a button, where clicking on it triggers a dialog allowing the user to choose a directory to save files in. This functiona ...

Top Method for Reloading Element-Specific JavaScript When Replacing Elements

Is there a better way to re-initialize JavaScript without needing a page refresh? I'm currently struggling with appending an MDBootstrap <select> tag, which involves more than just adding a child element. Instead, I have to remove the element an ...

Three.js: Modifying values within dat.GUI is not allowed

I have added a "comboBox" to my dat.GUI instance in order to select possible values. However, when I run my application, the dat.GUI appears with the comboBox but it seems to be frozen - I cannot change its default value. Below is the code snippet that dem ...

Bootstrap Carousel is still giving me trouble despite checking everything

Hey guys, could you take a look at my code? I really need help. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!-- jquery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/j ...

After upgrading to version 4.0.0 of typescript-eslint/parser, why is eslint having trouble recognizing JSX or certain react @types as undefined?"

In a large project built with ReactJs, the eslint rules are based on this specific eslint configuration: const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { ... After upgrading the library "@typescript-es ...

Attempting to use vue-test-utils-getting-started with the standard configuration results in a "Preset Not Found" error during

Currently, I am in the process of conducting a unit test by referring to the official guide provided. To do so, I have cloned the demonstration repository named vue-test-utils-getting-started. To replicate the issue, follow these steps: After cloning vu ...

What is the best way to extract multiple return values from the $.post function in jQuery?

How can I separate two variables retrieved from the server using the $.post method? Currently, when I attempt this, I receive a combined mixed value. Below is the code snippet: $(".spot_me").click(function() { var idea = $(this).attr("id"); ...

How to stop the default behavior of the tab key press in AngularJS

Hello, I am having an issue with an input field that triggers the add_plu() function when the tab key is pressed. While it does work as intended, the default action of the tab key (moving to the next element on the page) also occurs. I am wondering how I ...