creating a nested JavaScript object within another object

I need to create an object using the angular.forEach() function and then push another object while initializing all values to false. However, the current approach is causing errors.

How can I achieve this correctly? Using "item.id" and "index.id" does not result in the desired functionality. Here is a photo illustrating what I am trying to accomplish: link for image

        angular.forEach(metaData.validationRules, function (item, key) {
            // want to push object to another object
            angular.forEach(insarray.instances, function (index, key) {
               $scope.select = {
                    item.id: {
                        index.id:false
                    }
                }
            });
        });

Answer №1

Currently, this feature is not available but with the introduction of ES6, you can utilize a similar syntax as shown below.

angular.forEach(metaData.validationRules, function (item, key) {
  //Code snippet to add object to another object
  angular.forEach(insarray.instances, function (index, key) {
    $scope.select={
      [item.id]: {
        [index.id]:false
      }
    }
  });
});

Explore more examples here

Answer №2

The issue here lies in the incorrect method of setting the key for a key-value pair as demonstrated in your example. A more effective solution would involve:

$scope.selections = {};
angular.forEach(data.validationRules, function (rule, ruleKey) {
    $scope.selections[rule.id] = $scope.selections[rule.id] || {};

    angular.forEach(array.instances, function (instance, instanceKey) {
        $scope.selections[rule.id][instance.id] = false;
    });
});

It's essential to declare the new selections object outside of the loops to prevent overwriting the object in each iteration.

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

Error encountered when utilizing a specialized jQuery extension: "not a function"

Every time I attempt to execute this function (function($) { $.fn.generateURLHash = function() { return document.URL.substr(document.URL.indexOf('#')+1); }; })(jQuery); when I call $.generateURLHash(), an error pops up in th ...

Designing an Angular ui-router feature: Implementing a dynamic navbar that seamlessly integrates into all primary states as well as their sub-states

I am facing a challenge with my website's navbar. I want it to be displayed on most pages, but not all of them. I tried using ui-view to load it only for specific pages, but I have hit a roadblock. My goal is to connect the navbar to main states such ...

The Node.js error message "Module not found"

Currently, I am working through the node.js tutorial on Lynda.com and encountering an issue with the "Error: Cannot find module". Despite having the flight module listed in the package.json file, the error persists. Up until this point, everything has bee ...

How can I efficiently include all css from node_modules in vuejs?

For my Vue.js app built with the webpack template and vuetify, I am starting by importing the vuetify css in my App.vue. <style> @import '../node_modules/vuetify/dist/vuetify.min.css' </style> I'm wondering if this is the c ...

Having trouble retrieving alert message after submitting form using jquery

Trying to submit a form using jQuery, but when clicking on the submit button it displays a blank page. I understand that a blank page typically means the form has been submitted, but I want to show an alert() for testing purposes instead. However, it only ...

Guide on changing the CSS of MUI parent components to set the display of buttons to 'block' in React

I'm facing a challenge with my modal design for mobile view. I need the buttons to display in a stacked format, one above the other, taking up the full width of the modal. I've been exploring ways to override the existing CSS within the component ...

Are you currently working on a Ruby on Rails application?

Seeking guidance from the StackOverflow community on best practices when taking over a Rails app from another developer. I am stepping into a new role as the lead developer at my workplace. While I have experience in front-end, SQL/Mongo, Node.js, and kno ...

How can we utilize CSS floats to achieve maximum widths?

I currently have 5 divs that I need to structure in a specific way: Each div must have a minimum size of 100px The parent container should display as many divs as possible on the first row, with any remaining divs wrapping to new rows if necessary If the ...

Having trouble importing a module in my Node.js/Express application

I've encountered an issue while trying to import files into my node js server file. My usual method is correct in terms of paths, so I'm puzzled about what the error might be. import express from 'express' import mongoose from 'mon ...

The manner in which sessionStorage or localStorage is shared between different domains

I am looking to persist data across different domains using sessionStorage or localStorage. How can I achieve this? The data needs to be shared between a Vue project and a React project. English is not my strong suit, so I hope you are able to understand ...

Are there any limitations imposed on keydown events in JavaScript when attempting to modify the browser's

I attempted to implement a JavaScript keydown event that would refresh the page, but unfortunately, it did not function as intended. Interestingly, the same code works flawlessly when triggered by a button click event. I'm in search of a solution to r ...

Using javascript to overlay and position many images over another image

I've searched extensively but haven't been able to find any relevant answers here. Currently, I am developing a hockey scoring chance tracker. My goal is to display an image of the hockey ice where users can click to mark their input. Each click ...

What is the solution for getting rid of the "clear sort" state in an angular-ui-grid column header?

I am looking for information on how to remove the default behavior where the 3rd click disables sort and stays "neutral" on sortable headers. Having a disable sort state seems flawed as it does not change the sort order. How can I eliminate the 3rd state ...

Storing the path of a nested JSON object in a variable using recursion

Can the "path" of a JSON object be saved to a variable? For example, if we have the following: var obj = {"Mattress": { "productDelivered": "Arranged by Retailer", "productAge": { "ye ...

Which frameworks are categorised under Express-based frameworks?

Considering a job opportunity to develop a web app, one of the requirements is to "use node.js with an express based framework." My understanding is to use node.js with express.js, but what exactly does an express based framework entail? Does it refer to ...

Encountering a 404 error for core.js and browser.js while loading an Angular 2 app through system.src.js

I am new to Angular2 and have followed the Angular2 quickstart and tutorial to get started. Just to provide some context, when a user clicks on a link in the top navigation bar of my webapp, it triggers a server side request. The resulting page returned t ...

cheerio scraping results in an array that is devoid of any data

Struggling to extract data from a website with the URL https://buff.163.com/market/csgo#tab=buying&page_num=1 using request-promise and cheerio. Check out my code snippet below: const request = require('request-promise'); const cheerio = requ ...

Using JavaScript to create an array from information retrieved from an AJAX

Encountering difficulties in retrieving data from an AJAX file, I am attempting to modify the data source of a web application originally defined in JavaScript as: var ds = [ 'Sarah', 'John', 'Jack', 'Don', 'B ...

Monitoring an object with Angular.js $watch does not detect the addition of a new property as a change

Within my Angular.js directive, I have the following code snippet: scope.$watchCollection(function(){ return StatusTrackerService.eventCollection }, function(){ console.log("ssssssssssss"); console.log(StatusTracker ...

Using Selenium with JavaScript and Python to simulate key presses

Is there a way to simulate key presses as if typing on a keyboard? I am looking to programmatically click on an input element and then emulate the user typing by pressing keys. I prefer not to use XPath selectors combined with sendkeys or similar methods. ...