Transferring an Array into an Object within an Object Using Angular

I'm currently diving into Angular and I decided to tackle angular.copy with a simple example. My goal is to create an Object using a Service, and then create a new Object that only contains certain elements from the original Object.

Check out the full code example: HERE

This is how the "Data" Object looks like in the Service:

return {
    name: "hello",
    toys: ["asd", "lol"],
    food: ["apple"],
    phones: ["samsung", "lg", "iphone"]
};

In the Controller, I use angular.copy to duplicate the Object, create a new one, and add only specific elements from the original Object:

$scope.oldData = angular.copy(Data);
$scope.newData = {};

$scope.newData.name = oldData.name;
$scope.newData.toys = oldData.toys;
$scope.newData.phones = oldData.phones;

My expectation was to display just three elements for the user: the name, the toys array, and the phones array.

<h1>{{newData.name}}</h1>

<h1>Toys:</h1>
<ul>
  <li ng-repeat="toy in newData.toys">{{ toy }}</li>
</ul>


<h1>Phones:</h1>
<ul>
  <li ng-repeat="phone in newData.phones">{{ phone }}</li>
</ul>

However, it's not working as expected. Can anyone point me in the right direction on what I might be doing wrong?

Answer №1

oldData is a scope variable specific to AngularJS, not a regular JavaScript variable.

$scope.oldData

This means you would access it using $scope.oldData instead of just oldData.

Code Snippet

$scope.oldData = angular.copy(Data);
$scope.newData = {};

$scope.newData.name = $scope.oldData.name;

$scope.newData.toys = $scope.oldData.toys;

$scope.newData.phones = $scope.oldData.phones;

Alternatively, you could define it as var oldData if you prefer that syntax.

Check out the Demo

Answer №2

Make sure to include $scope before using oldData in your code. For an updated example, refer to the plunkr link below: http://plnkr.co/edit/abc123XYZ789?p=preview

 $scope.oldData = angular.copy(Data);
 $scope.newData = {};

 $scope.newData.name = $scope.oldData.name;

 $scope.newData.toys = $scope.oldData.toys;

 $scope.newData.phones = $scope.oldData.phones;

Answer №3

Make sure to update your code to reference $scope.oldData instead of oldData to avoid conflicts.

var oldData = angular.copy(Data);
$scope.newData = {};

$scope.newData.Name = $scope.oldData.name;

$scope.newData.toys = $scope.oldData.toys;

$scope.newData.phones = $scope.oldData.phones;

Check out the updated plunker here

Answer №4

Ensure to assign the value of $scope.oldData.name to $scope.newData.name when writing for the scope object $scope.newData.name = $scope.oldData.name; ...

Answer №5

Upon running the given code snippet, an error message popped up stating that oldData is not defined. The reason for this error is that the script is attempting to reference a variable called oldData which cannot be found within the current scope.

To resolve this issue, it is necessary to access oldData via $scope.oldData.name instead of simply oldData.name as oldData is attached to the $scope.

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 best way to determine the quantity of utilized elements in an array of structures in the C programming language?

Imagine this scenario: struct a b[4]; //some elements of b have been filled I am trying to determine the count of non-empty elements in b. Given that I'm unsure if b contains exactly 4 non-empty elements, is there a method to achieve this? ...

How can you integrate AngularJS-UI with JQuery for seamless functionality?

Currently, I am working through the AngularJS-UI tutorial and have hit a roadblock right at the beginning. I am attempting to implement a basic tooltip feature, all necessary JS files have been included but an error is being thrown by the angularJS-ui mod ...

Vue Dynamic Table Title

Is it possible to add labels to a pivot-table in Vue without affecting array indexes and drag-and-drop functionality as shown in the screenshot below? https://i.stack.imgur.com/5JTSM.png Are there alternative methods for implementing this feature? You c ...

Breaking up a word string using a comma delimiter in PHP

In one of my recipe ingredient groups, I need to divide a string of text with a comma when notes are specified for any given ingredient. For example - instead of displaying "1 onion red", I want it to display "1 onion, red". Despite trying to use implode, ...

Combine the results of callbacks executed in a loop and return the final concatenated value

I have a dilemma with my data stored in MongoDB. I am currently attempting to update the score whenever it is triggered. However, due to the nature of my task, I find myself needing to execute multiple queries depending on a loop. Ultimately, my goal is t ...

Setting up additional requirements in a subfolder within play.js

Seeking assistance with an issue in play.js on Sandbox. Attempting to install a dependency but my package.json is not located in the root folder; it's stored within a folder named frontend. How can I install them when the package.json is inside that f ...

swapping the final word in a string with Node.js or JavaScript

var str = "Demo Docs Version 1.0.1"; var gotWord = str.split(" ").splice(-1)[0] str = str.replace(gotWord, "testing"); console.log(str); If there is a space between words, I can replace the last word. But how do I replace the last word when ...

Improve performance by debouncing computed properties and getters in Vue

I'm having trouble getting debounce to work with computed properties and Vuex getters. The debounced functions are always returning undefined. Check out this JSFiddle for an example HTML: <div id="app"> <input v-model="text"> <di ...

Maintain original pitch of HTML video content (preservesPitch, mozPreservesPitch, webkitPreservesPitch)

I am attempting to turn off the preservesPitch feature on a video element that is playing in slow motion by adjusting the video's playbackRate. In Chrome, video.webkitPreservesPitch is not defined, and changing it to false or true doesn't affect ...

Methods for reloading the requirejs module

There are two modules: settingmap.js var settingMap = { scWidth : [4000, 6000, 8000], scHeight : [5000, 7000, 9000], bxWidth : [100, 90, 80], bxHeight : [100, 90, 80], totalTime : [50, 40, 30], level : [1, 2, 3], boxColor : [&a ...

JavaScript Arrays with Four Dimensions

Looking for a solution to generate arrays with any number of dimensions, including 4D arrays. I'm interested in being able to use the function to create an array and then access it like this: arr[3][2][23][12] = "amazing"; ...

Bluebird refuses to execute the then() function, despite the code that was functional before

I am in the process of constructing a node framework for my upcoming projects, with a focus on easy management. The framework already includes a configuration module. Recently, I implemented an error handler and made updates to the Config module to incorp ...

What could be causing the npm mysql module to malfunction when trying to initiate the 'connect()' function in a separate .js file?

When I call require('mysql') and use the function connect() everything works fine. However, if I try to call the 'connect()' function in another file, it throws an error saying connection.connect is not a function... Any suggestions on ...

Combining Mouseover and Click Events in Vue JS

Having four pictures, I want to display a specific component when hovering over them. However, I also need to bind the click event so that clicking on the picture will reveal the component. The challenge is that I am unable to simultaneously bind two event ...

Begin the loop in Java with a leap

Currently, I am developing a program using Java along with Selenium WebDriver. I am facing a challenge with the looping technique in Java. Here is the snippet of my code: Consider, rt = {Capacity Utilization,Overlay Report} fq = {15 Minute,Hourly,Daily ...

Adding an item to an object array in MongoDB can be achieved with the use of either the addToSet or push operators

I have a set of reviews in an array, and I am trying to implement addToSet functionality to add a review while ensuring that a user can only review once. Below is how my schema is structured: const sellerSchema = new mongoose.Schema({ user: { type: ...

Creating dynamic email templates in Node.js

I am working on a project using the MEAN stack and I need to implement email functionality. I have created separate email templates, but I want to include a common header and footer in all of them. Route.js router .route('/api/user/register&a ...

Can a virtual host proxy utilize an external IP address?

Currently, I have three node apps running on the same server but with different localhost ports. My goal is to create a router that acts as a proxy for each app and then place this proxy in a virtual host. While I am currently testing this setup on my loca ...

Issues with Angular Material Pagination functionality may be causing unexpected behavior

I'm facing an issue with displaying data in an HTML table using an API. I've tried to implement pagination to show 3 or 6 rows per page, but it's not working as expected. Currently, all the data is being displayed without any pagination, whe ...

"Optimizing reload time for DIV content with jQuery's .load function is proving to be

I am currently facing an issue with a div that displays data from a database and a form that updates item quantities. After submitting the form, the div refreshes while a modal with a bootstrap spinner pops up to indicate it is loading. The problem arises ...