What is the solution for untangling this complicated Javascript variable referencing issue?

Currently facing an issue that needs to be addressed:

app.controller 'MainCtrl', ($scope, TestData) ->
  $scope.name = 'World'
  TestData.get(0).then (data)->
    $scope.elem = data  
  TestData.get(1).then (data)->
    $scope.elem2 = data

  $scope.callFunc = ->
    TestData.modify1()
    TestData.modify2()

app.factory 'TestData', ($q,$timeout)->

  data = [{
    name: "TestData #1"
    id: 1
  },{
    name: "TestData #2"
    id: 2
  }]


  funcs = {}

  funcs.get = (id)->
    deferred = $q.defer()
    $timeout(->
      deferred.resolve(data[id])  
    ,500)
    return deferred.promise

  funcs.modify1 = ->
    data[0].name = "DataTest #1"

  funcs.modify2 = ->
    data[1] = {
      name: "DataTest #2"
      id
    }

  return funcs

In an attempt to update an element in an array, I find myself unsure of the best approach. It seems that simply replacing it will not solve the problem. How can this obstacle be overcome?

If it were a matter of just altering the name/id, there wouldn't be an issue. However, the models contain a variety of data that I wish to update collectively without modifying them individually.

A demonstration illustrating the issue can be found here: http://plnkr.co/edit/cBXJsIghlIeIUQGLfZfe?p=info

(Despite understanding the underlying reason for the difficulty, I am seeking the most efficient solution to resolve this predicament.)

Answer №1

If you want to transfer all the properties from object in to object out, this code snippet can help:

for key in in
  out[key] = in[key]

I'm not entirely familiar with Angular, but you may find some inspiration here: http://plnkr.co/edit/LKb6NQ4u0dORLya42LED

$scope.callFunc = ->
  TestData.modify $scope.elem, 0
  TestData.modifyAlt $scope.elem2, 1

...


funcs.modify = (incoming,i)->
  console.log "incoming:",incoming
  for key in incoming
    data[i][key] = incoming[key]

funcs.modifyAlt = (outgoing,i)->
  console.log "data[i]:",data[i]
  for key in data[i]
    outgoing[key] = data[i][key]

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 while trying to render a Threejs FBX Object - undefined 404 (Resource not found)

I am facing an issue while loading a set of .fbx objects using FBXLoader on a WebXR App. window.fbxLoader.load("/assets/modelate_FBX/Vaza%208067134/Vaza 8067134.fbx", function( object ) { const flower = this.scene.children.find(c => c.name ...

Encountering an issue with usememo in React js?

I'm currently experimenting with the useMemo hook in React JS. The goal is to sort an array of strings within a function. However, when I return the array from the function, only the first element is being returned. Can someone please assist me in ide ...

What is the best way to add a checkbox tag in Rails using JavaScript?

I am attempting to use javascript to append the values from option fields to checkboxes in Rails. Here is a snippet of my javascript code: $("#regions option").each(function(){ $("#region-checkboxes").append('<li><%= check_box_tag "region ...

Filter object in Angular to remove empty values

Below are the specific data sets: $scope.icons = [{ "id": 1, "bonuses": [ { "id": 1, "name": "Rob", "amount": 10, "foreman": 1, "percA": 1, "percB": 0 }, { "id": 2, "name": "Mark", "amount": 20, "foreman": 1, "percA": 1, "percB": 0 }, ] }, { ...

utilize the getStaticProps function within the specified component

I recently started a project using Next.js and TypeScript. I have a main component that is called in the index.js page, where I use the getStaticProps function. However, when I log the prop object returned by getStaticProps in my main component, it shows a ...

Ways to stop two JavaScript files from running at the same time

After combining two JavaScript files, I am facing some issues. The first file handles validation while the second one has an ajax plugin for form submission after validation. When I include these files in the header section, they both run simultaneously. H ...

Transform milliseconds into an ISODate representation

I have a MongoDB collection where records are stored with timestamp in milliseconds. I need to aggregate these records by hour and convert the timestamp to ISODate so that I can use MongoDB's built-in date operators ($hour, $month, etc.) Here is an e ...

"Data is not defined" error message is triggered when using jQuery DataTable Row Details

While utilizing jQuery Data Tables to construct a datatable with row details, I encountered an error in jquerydatatables.js: data is undefined The JavaScript code being used is: $(document).ready(function() { var dt = $('#tbl_cheque_history' ...

When you use the useState object in NextJS, the context object may appear to be empty

I've encountered an issue while trying to pass a context object in NextJS that uses data from a useState hook. Strangely, the state variable and setState functions are undefined when consumed. It's puzzling because substituting a simple variable ...

Issue with ng-pattern validation for email not functioning as expected

Currently, I am utilizing the following pattern for email validation var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3 ...

Utilizing the Pub/Sub architecture to integrate the kafka-node library within Node Js

Utilizing the kafka-node module in my NodeJs Microservise project, I am aiming to implement a Pub/Sub (publisher and subscriber) design pattern within the Functional programming paradigm. producer.js const client = new kafka.KafkaClient({ kafkaHost: ...

Triggering a jQuery event when a CSS property is altered

My current approach involves utilizing the .animate method to shift a div 100px to the right in just 1 second. Essentially, this means moving by 1px every 10ms. I am now exploring whether there exists an event that could be triggered after each individual ...

Upgrade to a more stable configuration version for Nodemailer as the current configuration is not supported. Consider down

I'm currently utilizing Nodemailer version 2.6.4 with Node version 6.9.1 var nodemailer = require("nodemailer"); var wellknown = require('nodemailer-wellknown'); var transporter = nodemailer.createTransport("SMTP",{ service: "yahoo", ...

Exploring the characteristics of images in Javascript

I've gone through my code multiple times but I just can't figure out why it's not functioning correctly... Could someone shed some light on this? What am I missing here? The purpose of the code is to allow users to input different values i ...

What purpose does the "io" cookie serve in Socket.IO?

Can someone explain the purpose of Socket.IO using the io cookie as a session cookie? I understand that it can be disabled, but I couldn't find any information on it in the documentation. Why is it turned on by default and what consequences would ther ...

What causes useEffect to trigger twice when an extra condition is included?

Attempting to create a countdown timer, but encountering an interesting issue... This code triggers twice in a row, causing the useEffect function to run twice per second. 'use client' import {useState, useEffect, useRef} from 'react' ...

Discover a method for bypassing the Quick Search Firefox feature and capturing the forward slash keypress

Currently, I am trying to capture the key press value of '191' for the forward slash (/) as part of a feature on my website. This functionality works perfectly on all browsers except for Firefox, where it conflicts with the Quick Search feature. ...

Presence detected: Discord bot appears online but is missing from members list

I am embarking on the journey of creating my first Discord bot. After installing NodeJS on my computer, I used the Discord developer tools to create the app, turned it into a bot, obtained the token, selected privileges, and added the bot to my server. I ...

No response text returned from the local Ajax request

Currently, I am facing a challenge while attempting to send an ajax call from the client to my server containing data related to an input parameter. The issue is that although I can view the data in my server's console, it does not display in the brow ...

Utilizing JavaScript to assign a CSS class to an <li> list item

I am working on a page that includes a menu feature: https://jsfiddle.net/dva4zo8t/ When a menu button is clicked, the color changes and I need to retain this color even after the page is reloaded: $('[id*="button"]').click(function() { $( ...