Discovering and swapping values within nested objects

I've encountered a challenge that I need help with:

In my nested object, I receive a response from the server containing an object with updated values. My goal is to locate this object within my nested structure and replace it.

The structure of my object looks like this:

$scope.page = {
  id: 5,
  label: 'myPage',
  items : [
    {
      "type": "Container",
      "id": 1,
      "label": "header",
      "items": [
        {
          "type": "Container",
          "id": 2,
          "label": "left",
          "items": [
            {
              "type": "Menu",
              "label": "settings-menu",
              "id": "5"
            },
            {
              "type": "Menu",
              "label": "main-menu",
              "id": "7"
            }
          ]
        },
        {
          "type": "Container",
          "id": 4,
          "label": "right",
          "items": [
            {
              "type": "Post",
              "label": "contact",
              "id": "25"
            }
          ]
        }
      ]
    },
    {
      "type": "Postlist",
      "label": "nieuwsberichten",
      "id": "17"
    },
    {
      "type": "HTML",
      "label": "over deze site",
      "id": "18"
    },
    {
      "type": "Other",
      "label": "twitter feed",
      "id": "19"
    }
  ]
}

A new object is received from the server:

var newItem = {
  "type": "Post",
  "label": "contact",
  "id": "25"
}

What is the correct method to update the object within $scope.page? I have attempted the following approaches:

$scope.findAndReplace(newItem,$scope.page.items);

$scope.findAndReplace = function(newItem, items) {
  for (var i = 0; i < items.length; i++) {
    if (items[i].id == newItem.id) {
      items[i] = newItem;
    } else if (items[i].items) {
      $scope.findAndReplace(newItem, items[i].items);
    }
  }
}

and:

var oldItem = $scope.findById(item.id, $scope.page.items);
oldItem = newItem;

$scope.findById = function(id, items) {
  var match = null;
  angular.forEach(items, function(i){
    if (match == null) {
      if (i.id == id) {
        match = i;
      } else if (i.items) {
         match = $scope.findById(id, i.items)
      }
    }
  })
  return match;
}

However, neither of these solutions seem to be working due to the nested loops causing the object not to be the one in $scope.page anymore.

Does anyone have any suggestions on how to tackle this issue?

Answer №1

It appears that your example is correct, but for some reason it isn't functioning as expected.

Both of the options provided are not functioning properly. This is likely due to the nested loops causing the object to no longer be in $scope.page.

To maintain the object reference, try utilizing angular.copy(newItem, oldItem)

Answer №2

Hello, I have prepared a demonstration for you. click here to view the demonstration

    for(var index=0; index < $scope.page.items.length; index++) {
    var temporaryObject = $scope.page.items[index];
  if(temporaryObject.hasOwnProperty('items')) {
    // check inside
    for(var index1=0; index1<temporaryObject.items.length; index1++ ) {
        var innerObject = temporaryObject.items[index1];
      // check for next level
      if(innerObject.hasOwnProperty('items')) {
        for(var counter=0; counter< innerObject.items.length; counter++) {
            var thirdTemporary = innerObject.items[counter];
            console.log('3rd level inner object', thirdTmp);
          if(thirdTemporary.id === newItem.id) {
            innerObject.items[counter] = newItem;
            temporaryObject.items[index1] = innerObject;
            $scope.page.items[index] = temporaryObject;
          }
        }
      }

    }
  } else if(temporaryObject.id === newItem.id) {
    $scope.page.items[index] = newItem;
  }
};

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 display the currently selected value in a Vue select drop down?

Is there a way to make the selected item in a custom component dropdown appear, similar to this Vue.js question? I have debug output within my single file component (SFC). <script> export default { props: ['modelValue', 'options&apos ...

Having trouble with nested requests and appending using Jquery or JavaScript?

Greetings everyone, I want to apologize in advance for any spelling errors or mistakes in my message. I struggle with dyslexia and other learning difficulties, so please bear with me. I am using this time during lockdown to learn something new. This is my ...

How can a method inside an object property of the same class be invoked in JavaScript?

I'm faced with a bit of confusion here. I have a class property called hotspot of type object, declared as follows: Cannon.prototype.hotspot = {stuff: this.blah(...) }; The method blah() is actually a prototype of the same 'class': Canno ...

What could be causing my divs to collide with each other in a Javascript environment?

As you may be aware, my current task involves assigning random positions from a list to various div elements. The code I am using to achieve this is as follows: var list = [100,210,320,430]; var square1 = document.getElementById("square1") var sq ...

What steps can I take to position tsParticles behind all other elements in my NextJS project?

In full disclosure, I am not a web developer, so my setup may be incorrect. Currently, the particles are covering all other elements on the page. I would like them to be positioned behind the rest of the elements and only show as a background. import Imag ...

Tips for including vue-autonumeric in your webpack 2 setup

Encountering a problem while bundling the vue-autonumeric package with Webpack 2, where the dependency AutoNumeric is not being found properly. Although there is an alias set up in the configuration that works fine with webpack 3, it seems to fail when wo ...

The DiscordBot is configured to send a personalized direct message to users who have chosen a specific role

Having trouble setting up my bot to send a DM to new members who choose the Advertising role, and I can't figure out why. I'm fairly new to this. const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ ...

Creating a Google Captcha with validation is a straightforward process that can enhance the

I am having issues with adding Google Captcha to my form. Despite all fields working properly, the Captcha integration seems to be causing some disruptions. I have included my code below. Thank you in advance for your help. Please also check the following ...

implementing data in a single component using vue.js

I am facing an issue with a component where I need to fetch data using an ajax call. The component is being called correctly and the data is returned in the ajax call, but I am struggling to assign it to the data in the template? <template> < ...

The functionality of $(selector).css() seems to be malfunctioning

I currently have an html div element stored in a variable var rows = ""; rows += "<div>1111 : Hi there</div>"; Despite multiple attempts, I have failed to add a background color to this div using the following methods: 1. $(rows).css({&apos ...

What is the method for altering the appearance of grid columns with javascript?

What modifications do I need to make in JTML and Javascript? var opac; function checkfun() { opac=(Array.from(document.querySelectorAll('input[type="checkbox"]')) .filter((checkbox)=>checkbo ...

Error message: "Unable to locate module for split-pane-react in Jest"

Attempting to run Jest tests on my component with [email protected] in a Next.js project using typescript. Encountering the following error: Cannot locate module 'split-pane-react' from 'my component path' when running the test ca ...

Ways to retrieve base64 encoded information from an image within an HTML document

On my registration form, users have the option to select an avatar from 2 choices: Select a default avatar Upload their own custom avatar This is how I have implemented it in my HTML page. <img id="preview" src="img/default_1.png"> The chosen av ...

Breaking down a div with jQuery - tips and tricks!

I have a question regarding jQuery. Consider the following structure: <div class="page"> <p>Lorem ipsum....</p> <p>Lorem ipsum....</p> ... </div> I want to transform it into this format: <div class="pa ...

Transferring information to an outside document using Ajax

My code works perfectly when I use this: ajax.open("post","a.php",true); However, the problem arises when I attempt to send data to an external file like this: ajax.open("post","http://www.example.com/a.php",true); Unfortunately, it doesn't work i ...

Trouble with formatting a HTML form

I have been working on dynamically creating HTML forms using a function called makeInput(). However, I am facing an issue where the text input boxes are appearing next to each other when I click the "Add Course" button, instead of one per line. Below is ...

How to retrieve values using AngularJS ng-repeat

I received the following response: myresponse test: { "credit": { "1500000": [{ "date": "2016-07-21", "balance": -1528750, "category": "Transfer out", "narration": "test1", "amount": ...

Prevent Repetition of Meta Descriptions and Keywords within Next.js

I'm currently working on my website using Next.js. In order to enhance the SEO performance of my site, I am making an effort to steer clear of duplicate meta tags. My Inquiry According to Next's official documentation, they suggest that using t ...

Creating an image from a webpage by utilizing JavaScript

Similar Question: Using HTML5/Canvas/Javascript to capture web page as an image I have a webpage where I fetch details from a database and display them in a table format. I would like to save this page as an image so that I can email it to the user. C ...

Tips on resolving JavaScript's failure to adjust to the latest HTML inputs

I'm working on a homepage where users can choose their preferred search engine. The issue I'm facing is that even if they switch between search engines, the result remains the same. I've experimented with if-then statements, but the selecti ...