Generate an identical array using a fresh one

When working with an array to populate form fields and send data to a server, it's important to handle updating the array with new values. Below is an example showcasing this process:

View the example here

Highlighted code snippets:

HTML:

<div ng-app='myApp' ng-controller='mycontroller'>

    <div data-ng-repeat="item in myNewArray.newArray track by $index">
        <div ng-if="item.attrType == 'text'">
            <input id="form-f{{$index}}" type="text" placeholder="{{item.attrname}}" data-ng-model="item.attrValue"/>
        </div>
    </div>
    <div data-ng-repeat="object in getItems.data">
        <div data-ng-repeat="att in object.objects">
            <ul ng-repeat="data in att.attributes">
                <li>
                    <a ng-click="pushItems(att.name, data)">{{data.attrname}}</a>
                </li>
            </ul>
        </div>

    </div>


    <p>{{showNewJson()}}</p>
</div>

JS:

var myApp = angular.module('myApp',[]);

// Angular controller function
myApp.controller("mycontroller", ["$scope", "$http",
    function($scope, $http){
        // Initial data structure
        $scope.getItems = {
    "data": [
        {
            "label": "first",
            "objects": [
                {
                    "name": "firstObj",
                    "attributes": [
                        {
                            "attrname": "asd1",
                            "attrValue": "",
                            "attrType":"text"
                        },
                        {
                            "attrname": "asd2",
                            "attrValue": "",
                            "attrType":"text"
                        }
                    ]
                }
            ],
            "key": "bolla"
        },
        {
            "label": "second",
            "objects": [
                {
                    "name": "secondObj",
                    "attributes": [
                        {
                            "attrname": "asd",
                            "attrValue": "",
                            "attrType":"text"
                        },
                        {
                            "attrname": "asd3",
                            "attrValue": "",
                            "attrType":"text"
                        }
                    ]
                }
            ],
            "key": "2"
        }
    ]

};
    $scope.filterSelected = $scope.getItems.data[0].objects;

        $scope.myNewArray = {
            newArray: [

            ]
        }
        // Function to update the array with new values
        $scope.pushItems = function pushItems(attribute, items) {
            $scope.myNewArray.newArray.push(angular.copy(attribute), angular.copy(items));
            console.log($scope.myNewArray);
        }

        // Function to display the updated JSON
        $scope.showNewJson = function() {
            return $scope.myNewArray;
        }
}]);

Note: This example utilizes AngularJS for data handling.

To view the updated version, visit: Updated JSFiddle link

Below is the corrected JSON structure:

{
    "objects": [
        {
            "name": "firstObj",
            "attributes": [
                {
                    "attrname": "asd1",
                    "attrValue": "asdas",
                    "attrType": "text"
                },
                {
                    "attrname": "asd2",
                    "attrValue": "sadsa",
                    "attrType": "text"
                },
                {
                    "name": "secondObj",
                    "attributes": [
                        {
                            "attrname": "asd3",
                            "attrValue": "tttt",
                            "attrType": "text"
                        },
                        {
                            "attrname": "asd4",
                            "attrValue": "qqq",
                            "attrType": "text"
                        }
                    ]
                }
            ]
        }
    ]
}

Answer №1

Here is the solution I came up with - https://jsfiddle.net/vuqcopm7/8/

$scope.myNewArray = {
            items: [

            ]
        }

        $scope.createJSONData = function(key, values) {
            var object = {};
            object.name = angular.copy(key);
            object.values = [];
            object.values.push(angular.copy(values));
            return object;
        }

        $scope.checkIfKeyExists = function(key) {        
            for(var i=0; i<$scope.myNewArray.items.length; i++) {                
                if($scope.myNewArray.items[i]["name"] === key) {
                    return i;
                }
            }
            return -1;
        }

        $scope.addItems = function addItems(key, values) {
            var index = $scope.checkIfKeyExists(key);
            if(index === -1) {
                var newObj = $scope.createJSONData(key, values);
                $scope.myNewArray.items.push(newObj);
            }
            else {
                $scope.myNewArray.items[index].values.push(values);
            }


            //console.log($scope.myNewArray);
        }

        $scope.displayNewJSON = function() {
            return $scope.myNewArray;
        }

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

What is the correct way to configure environment variables in a Next.js application deployed on Vercel?

As I develop my web app in Next.js, I have been conducting tests to ensure its functionality. Currently, my process involves pushing the code to GitHub and deploying the project on Vercel. Incorporating Google APIs dependencies required me to obtain a Cli ...

Is there a more efficient method for converting an array of objects?

Is there a more efficient way to change just one value in an array without iterating through every element? I've included the code below where I am trying to update the contact number for each user in an array. Although my current solution works, it ...

Leverage the power of Angular's route resolve function

Can anyone assist me with a problem I'm facing? I am looking for a way to delay the display of a view until my data is loaded. After some research, I was thinking of using a resolve in the route, but I can't seem to figure out how to implement it ...

Every time I try to retrieve a specific field value from a document in MongoDB, all I seem to get is [object Promise]

I need assistance with retrieving a specific field value from a Mongoose document. Within my recipe schema, I have defined a field called "postedBy" which represents the _id of the person who submitted the recipe. Below is a snippet of the recipe model: l ...

Tips on maintaining the position of images in Fabric.js

Currently, I am working on image processing using fabric js. Dealing with large images requires me to save copies of canvases after processing to enable faster display next time using jQuery's id.show feature. However, my goal is to render images in t ...

Ending the loop of a jQuery JSON array when reaching the final row

I have a function that retrieves a JSON array and shows the results as a list with ten items. However, if there are fewer than ten results, it starts over from the beginning. This is my code: $.ajax({ url: 'http://www.entertainmentcocktail.com/c ...

Can you elaborate on this specific JavaScript concept?

I'm not very knowledgeable about javascript. Could someone please explain this structure to me? [{a:"asdfas"},{a:"ghdfh",i:54},{i:76,j:578}] What exactly is being declared in this structure? It appears to be an array with 3 elements, correct? Each e ...

Python Selenium code is encountering a "Element not found" exception

I am facing difficulty in finding the specific element on the webpage. Even though I can visually see it on the webpage, I am unable to locate it programmatically. I have tried using explicit waits and Xpath to pinpoint the element without success. Despite ...

Adequate parameters are necessary for an express callback function beyond just (req, res)

Working on my express app, I've come across a requirement where only (req, res, next, err) can be passed into the callbacks. This is what I had that worked. function listEvents(auth, req, res, email, authURL = ""){ ... var calendar = google.calendar ...

What steps can I take to personalize Material UI within a React application?

As someone who is new to this UI framework and React, I have been tasked with developing an application that requires more design patterns. I specifically chose a framework that does not depend on jQuery code. However, I am facing challenges when it comes ...

React does not allow functions as child elements. I have thoroughly reviewed my code and cannot identify the source of this issue

I have a parent component with a lot of logic and several other components that are functional components with only the return JSX method. I kept getting a lot of "Functions are not valid as a React child" errors, so I made some changes to fix this. I thou ...

Testing routes in AngularJS with "resolve" functionality

I'm facing a challenge while trying to unit test one of my routes, receiving the dreaded "Error: Unexpected request" message. The route in question includes a "resolve" parameter and is structured like this: when('/Users', { ...

What is the technique for adjusting the background while rotating the corner?

Is it possible to position a background image in the corner while rotating another image? rotate: $('#ship').css({ transform: 'rotate(' + corner + 'deg)' }); } move background: starx[i]=starx[i]+... s ...

Distinguish between a function and a constructor during execution

As I work with TypeScript, I am creating a function that accepts an error factory as an argument. This factory can be either a class name or a function. The function looks something like this: // Alias from class-transformer package type ClassConstructor& ...

Conceal the div element without revealing it beforehand

Is there a method to conceal a div without it initially loading? When I attempt to hide the div, it briefly appears for about 0.5 seconds before disappearing, which makes the animation look unattractive. Is there a way to prevent this, or am I approaching ...

Utilizing a global variable within a JavaScript function to enable its usage across different PHP pages

In my script, there is a code snippet that sets different grid sizes based on user selection. The goal is to store this selection in a variable that can be accessed in PHP code on another page to tailor the output accordingly. After attempting to add a ne ...

While creating a React app, Docker becomes stuck due to a hangup when checking the core-js dependency

I've hit a roadblock in the build process. I'm working on an M1 Mac Mini and have attempted to build in both arm64 and x86_64 terminals, but the outcome is consistently the same. npm info lifecycle @babel/<a href="/cdn-cgi/l/email-protection" ...

Guide on how to import image data instead of an image using THREE.js in javascript

I wrote a JavaScript function that loads an image as a texture: var loader = new THREE.TextureLoader(); loader.load( 'textures/canvas1.png', function ( texture ) { var geometry = new THREE.SphereGeometry( 200, 20, 20 ); var material = n ...

Linking create-react-app reactJs with mysql

I am facing an issue connecting my create-react-app with MySQL using npm. It works fine in nodejs when I tried separately without npm. However, when I attempt to connect using npm install mysql, I get the following error: TypeError: http.IncomingMessa ...

Which is more advantageous in this scenario: using .fail() or .timeout()?

When it comes to handling timeouts on my $.ajax() calls for a jQueryMobile project, I have discovered two potential methods. The .fail() function appears to be the more generic option: if the call fails for any reason, an error stack is returned and then ...