Adding data to a JSON object using AngularJS

When attempting to insert an object into a JSON object, I am encountering an issue where it duplicates the JSON object. Here is a breakdown of the scenario:

<input type="text" style="width: 40% !important;" placeholder="Nom" class="input-sm"  ng-model="company.link.nom"  />
<input type="text" style="width: 40% !important;" placeholder="Lien" class="input-sm"  ng-model="company.link.value"  />
<a class="btn btn-wide btn-primary" ng-click="company.addExternalLinktoGrid()"><i class="fa fa-plus"></i> Add </a>

The function addExternalLinktoGrid handles this process:

var linkJsonObj = [];
var cp=1;
company.addExternalLinktoGrid = function() {
  company.link.id=cp;
  currentObj.push(company.link);
  console.log(JSON.stringify(company.link));
  linkJsonObj.push(company.link);
  console.log(JSON.stringify(linkJsonObj));
  cp++;
}

For instance, if we add a new object with values company.link.nom="toto" and company.link.value="titi",linkJsonObj will display:

[{"nom":"toto","value":"titi","id":1}]

If we then add another object with values company.link.nom="momo" and company.link.value="mimi", linkJsonObj ends up displaying:

[{"nom":"momo","value":"mimi","id":2},
 {"nom":"momo","value":"mimi","id":2}]

This unexpected duplication occurs. The intended output should be:

[{"nom":"toto","value":"titi","id":1},
 {"nom":"momo","value":"mimi","id":2}]

If anyone has insight or assistance, it would be greatly appreciated.

Answer №1

When dealing with objects in JavaScript, it's important to remember that if you push an object to an array, it is passed by reference. This means that any changes you make to the object will be reflected in the array as well. To avoid this, you should create a copy of the object before pushing it to the array. Otherwise, if you push the same object multiple times, the array will contain multiple references to the original object.

var newObject = {
  nom: company.link.nom,
  value: company.link.value,
  id: cp
}
linkJsonObj.push(newObject);

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

Invoking PHP code from within Javascript will output the function as a direct string

I seem to be going in circles and missing something silly... My setup involves using CodeIgniter on the server-side and Bootstrap on the client, but that's not really the issue here... I am attempting to access a PHP value within a JavaScript functi ...

Prevent memory leakage by utilizing Angular's $interval feature in countdown processes

I have a controller set up to handle a countdown feature: var addzero; addzero = function(number) { if (number < 10) { return '0' + number; } return number; }; angular.module('theapp').controller('TematicCountdownCo ...

Utilizing JSON to showcase MySQL data on Android Studio

I am facing an issue with displaying data from MySQL into Android using TextView. When running the app, it crashes and force stops itself. Can someone assist me in resolving this problem? Any suggestions or ideas would be greatly appreciated. dbconfig.php ...

Combine package routes with main app routes in Express application

Currently, I am building my own MEAN stack from scratch. My goal is to organize it with a horizontal architecture similar to how mean.io structures theirs. In this setup, each package will have its unique server and public folder along with their respectiv ...

Showcasing PHP variables within HTML using jQuery

I am currently looking for the best way to showcase information stored in a PHP variable, retrieved from a MySQL database. My initial thought was to use jQuery. Here are my questions: When a user inputs a number into a field, I receive that Member' ...

Utilize Angular's $state service within a configuration setting to automatically redirect to a specific state using an interceptor

I'm working with restangular and have set up an interceptor to handle 401 responses by redirecting to another state. The issue is that angular only allows the injection of providers, not services, in config. Is there a way to access the $state: ng.u ...

Out of the box, Next.js is equipped with a standard error message stating: "TypeError: Cannot read properties of null (reading 'useContext')"

After just setting up next.js for my upcoming website, I ran into some unexpected errors while trying to host it with "next". The specific error message I encountered was: TypeError: Cannot read properties of null (reading 'useContext') This iss ...

Exploring RPG YAJL's ability to parse nested arrays

I am new to RPG and feeling a bit overwhelmed with this task. I have an array called "data" that contains information which I can parse easily. However, within the "data" array, there is another array called "cargoLoaded" that holds a single item named "ca ...

Navigating to a parent URL where the Angular configuration is set can be achieved by following these steps

My application revolves around a webpage created with the use of node and angular. On the root URL (/), I have incorporated a signup and login form without the use of Angular. Upon successful login, Angular scripts and configuration files are loaded on the ...

Step-by-step guide on displaying elements within an array of objects

Upon receiving an object from a website, I discovered that it includes an array of objects along with other parameters. When I use console.log(req.body.cart), the output is [ { title: 'iphone 6', cost: '650' } ], but I only require the ...

Invoking a function passed via props that utilizes react-router's features

I'm really struggling to grasp this problem. Is there anyone here who could help me out? I have a component where I pass a method called this.fetchContent as props named Filter. This method triggers an action creator that uses axios with Redux to fetc ...

Error: Unable to retrieve the value as the property is null

I'm a beginner in jQuery and I'm attempting to create a login form that displays a message when the user enters a short username. However, despite my efforts, the button does not trigger any action when clicked. Upon checking the console, it indi ...

What is the best way to send an array and file in the same AJAX request?

When attempting to send both an image file and an array through my AJAX request to a PHP script, I encountered an issue where either the array or the image file doesn't appear. The problem seems to stem from the specific lines that need to be added to ...

Ways to implement standard sorting in react-table

Currently, I am utilizing react-table v7 to generate tables. You can find more information about react-table at https://www.npmjs.com/package/react-table. While working with the table, I was able to implement sorting for all columns by following this e ...

Tips for updating marker information upon clicking in React-leaflet

I am working on a React-leaflet map that displays markers on the left side, while on the right side, there is a list of point names. I want the behavior to be such that when a marker is clicked, the corresponding point name moves to the top of the list. Th ...

I'm having issues with my page due to the ui.bootstrap uibModal in Angular

I have been diving into learning Angular recently, and while following a tutorial, I realized it was based on an older version of Angular. This has caused issues with the part of the tutorial that covers using ui.bootstrap. Currently, I am working with An ...

Enhance JSON data with AngularJS through interactive form editing

Attempting to create an editable TreeView in AngularJS using JSON data is proving to be a challenge. The goal is to extract a node value from the JSON and allow editing through forms, with the original JSON updating immediately during the editing process. ...

Canvas not displaying image in JavaScript

I have a bird object with a draw function defined, but for some reason, the image is not showing up when called in the render function. Can someone please help me figure out what I'm doing wrong? Thanks in advance. EDIT: Upon further investigation, I ...

When running npm install -g, the package is being installed into a global directory on

For a considerable amount of time, I have been working with node and npm. Now, as I embark on a more extensive project using these tools, I've encountered an issue. Whenever I execute 'sudo npm install -g', the installation is directed to &a ...

The Interactive Menu Toggler: A jQuery Solution

$(window).on('resize', function() { if ( $( window ).width() > 768 ) { $('#menu-main-navigation').show(); } }); $('#nav-toggle').on('click', function() { // start of the nav toggle $('#m ...