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

When working with NextJs, you may encounter a ValidationError indicating that the configuration object is invalid. This error occurs when Webpack has been initialized with a configuration object that doesn't

After upgrading from Next v12 to v12.2.3, I encountered a problem when running "yarn dev" with a new middleware.js file in the root directory: ValidationError: Invalid configuration object. Webpack initialization error due to mismatched API schema. - Deta ...

Ways to display a US map using d3.js with state names positioned outside each state and pointing towards it

Currently, I am working with d3.js and d3-geo to create a map of the USA. My goal is to display the names of some states inside the state boundaries itself, while others should have their names positioned outside the map with lines pointing to the correspo ...

Creating a custom ID for a Firebase POST request

Is it possible to assign a custom ID in Firebase when using the POST method? For example: { "users": { "user_one": { "username": "jdoe", "password": "123" } } } I'm currently working on a Vue.js project and I want to save ...

Python: "Converting a boolean value to a JSON string with quotes"

Hello everyone, I'm facing a problem with a requirement. Typically, when converting a Python boolean to JSON format, the solution is as follows: >>>data = {'key1': True} >>>data_json = json.dumps(data) >>>print d ...

Improving animation performance on mobile devices using AngularJS

I've reached the final stages of developing a mobile application using AngularJS wrapped in a cordova webview. However, I'm encountering some issues with the panel transition animations. After experiencing strange behavior with ngAnimate, I deci ...

The display message in Javascript after replacing a specific string with a variable

I'm currently working on a task that involves extracting numbers from a text input, specifically the first section after splitting it. To test this functionality, I want to display the result using an alert. The text input provided is expected to be ...

Tips for transferring the name field to a different page upon clicking

There are two pages in my project - the first one is called ItemMenuPage and the second one is called CartPage. The functionality I am trying to achieve is that when a user clicks on any item name on the ItemMenuPage, it should navigate to the CartPage, wi ...

What steps do I need to take to make this JavaScript code function properly? How can I create a carbon copy email setup in

Recently, I've been struggling to implement this particular code on my website as I am not very proficient in JavaScript. Despite searching for various online resources, none of them seem to address my issue. This code is meant to be a part of a form ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...

The height of the browser action will not return to its original state

I'm currently working on an extension that provides responses based on user text input. However, I'm running into an issue where the height of the browser action won't reset properly. I've tried various methods to fix this problem, in ...

I aim to generate a JavaScript string that, when placed within a div tag, will display as a list

I need assistance with formatting a string that contains a list of items to display in a specific way within a div tag using JavaScript. The string has multiple items that I wish to show as a bulleted list. Here is an example of the string: const items = & ...

The text/font-weight of the header button is mysteriously shifting without warning

While creating a header for my webpage, I encountered an issue where the text family was changing when the dropdown menu was launched in Safari 8. Curiously, this behavior did not occur when using Chrome to launch the jQuery function. Even after attempting ...

Alternatives to getElementById in AngularJS

I am currently utilizing the jquery CircularSlider Plugin to implement 4 sliders on a single page. I have customized values for each slider and now I am looking to retrieve the value of each slider using an angularjs Directive. var intensity = $('#i ...

The code "Grunt server" was not recognized as a valid command in the

I recently set up Grunt in my project directory with the following command: npm install grunt However, when I tried to run Grunt server in my project directory, it returned a "command not found" error. Raj$ grunt server -bash: grunt: command not found ...

What is the process of sending an HTTP/HTTPS request from a Node.js server?

Currently diving into the world of Node.js, I am experimenting with using a Node.js Application on cPanel to generate a JSON response upon accessing its URL. Upon visiting the app's URL, it seems that the Node.js server is functioning correctly. Afte ...

Generate an additional element for each element when clicked, triggering an error warning

When creating a form, I want to display an error message next to each invalid element when the submit button is clicked. Although I am close, the issue is that it adds the span tag twice after the element if two elements are invalid. I need it to be added ...

Utilizing Node.js and Mongoose, effortlessly update data in Mongo DB regardless of the existence of the collection

How can I update a field that may or may not exist? I attempted the following code: db.foo.update( { site: '"wisdom'}, { $set: {'club': 'fc barcelona'}}, (upsert=true) ) ...

Is it better to specify one root element or render the entire layout in ReactDOM.render()?

Currently in the process of learning React.js and I have a question. Is it more beneficial to keep my ReactDOM.render() as it is currently set up: ReactDOM.render( <div className="container"> <div className="row"> <div className ...

Delete an item from an array based on its index within the props

I am attempting to remove a specific value by its index in the props array that was passed from another component. const updatedData = [...this.props.data].splice([...this.props.data].indexOf(oldData), 1); const {tableData, ...application} = oldData; this ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...