Guide to locating a particular node within an array of nested objects by utilizing the object

Dealing with an array of nested objects, the goal is to compare values with a flat array and update the property matchFound.

If the parent's matchFound is true, then all its children should inherit this value.

treeData = [{
    field: 'make',
    name: 'Infiniti',
    matchFound: null,
    children: [{
        field: 'model',
        name: 'G50',
        matchFound: null,
        children: [{
            field: 'trim',
            name: 'Pure AWD',
            matchFound: null,
          },
          {
            field: 'trim',
            name: 'Luxe',
            matchFound: null,
          },
        ],
      },
      ...
    ],
  },
  ...
];

The task involves scanning the flatData array to locate the corresponding node in treeData and updating the properties accordingly. For example, { make: "BMW" } - It should update {field: 'make', name: 'BMW', matchFound: true,...}, and all its children.

{ make: "Infiniti", model: "G50", trim: "Luxe" } should only update the matchFound of "Luxe".

The main issue lies in identifying the correct node in treeData using flatData. If altering the structure of flatData can assist in solving the problem, that step can also be taken.

   flatData = [{
      make: "Infiniti",
      model: "G50",
      trim: "Luxe"
    }, ...]

An attempt was made to convert flatData into the treeData structure but it did not yield the expected results.

[{
        field: 'make',
        name: 'Infiniti',
        matchFound: null,
        children: [...],
      },
      ...
    ];

The proposed solution is far from ideal as there are difficulties in locating the correct node in treeData.

for (const item of this.flatData) {
  for (const [key, value] of Object.entries(item)) {
    for (let i = 0; i < this.treeData.length; i++) {
      if (this.treeData[i].name === `${value}`) {
        this.treeData[i].matchFound = true;
        if (this.treeData[i].hasOwnProperty('children')) {
          this.updateAllChildren(i, this.treeData[i].children);
          }
        }
      }
    }
  }

  // Function to set matchFound true for all children
  function updateAllChildren(index, items) {
    for (let j = 0; j < items.length; j++) {
      this.treeData[index].children[j].matchFound = true;
      if (this.treeData[index].children[j].hasOwnProperty('children')) {
        for (let k = 0; k < this.treeData[index].children[j].children.length; k++) {
            this.treeData[index].children[j].children[k].matchFound = true;
        }
      }
    }
  }

Answer №1

Is it possible to determine the number of levels needed to travel based on the number of object keys? For instance, in the case of { make: "BMW" }, there is one key, allowing you to navigate to the first level and locate the object where name === 'BMW'.

In the scenario of

{ make: "Infiniti", model: "G50", trim: "Luxe" }
, you would need to traverse 3 levels. The first level involves finding the object with name equal to "Infiniti", then moving down one level to search for name equal to "G50". Once that object is located, another level down is required to find the object matching name equal to "Luxe". This process is crucial for pinpointing your target. Subsequently, set matchFound to true for that object and its subobjects.

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

"Why does the form.submit() function fail in IE9 when the form is in an iframe and the user is coming from Gmail

I have recently developed a function within my CodeIgniter framework that allows me to send emails with a backlink to my site. The link directs users to a page on my website that includes an iframe. Within this iframe, I have implemented a file input form ...

Guide to integrating various HTML files into a single HTML file with the help of Vue.js

Although I am familiar with using require_once() in PHP, unfortunately, I am unable to use PHP in my current project. I attempted to use w3-include from W3Schools as an alternative, but encountered issues with loading my scripts. Even utilizing JavaScript ...

Receive live feedback from shell_exec command as it runs

I have been working on a PHP-scripted web page that takes the filename of a previously uploaded JFFS2 image on the server. The goal is to flash a partition with this image and display the results. Previously, I had used the following code: $tmp = shell_ex ...

The table is hidden and the buttons are unresponsive when inserted using jQuery

Exploring blueimp's jQuery-File-Upload Demo has been occupying my time recently. After studying it for several days, I feel like I've gained a solid grasp of how it functions. However, as someone with limited experience in web development, there ...

Developing a system mode called "night mode"

I've decided to incorporate a dark mode feature into my Wordpress theme. Creating both dark and light modes was a breeze, but now I want to add a third mode that serves as the default for pages. This new mode will automatically switch between dark a ...

How can I trigger a method after the user has finished selecting items in a v-autocomplete with multiple selection using Vuetify?

After multiple selections are made in a v-autocomplete, I need to trigger a method. However, the @input and @change events fire after each selection, not after the full batch of selections. Is there an event that triggers when the dropdown menu closes? Al ...

The retrieved item has not been linked to the React state

After successfully fetching data on an object, I am attempting to assign it to the state variable movie. However, when I log it to the console, it shows as undefined. import React, {useState, useEffect} from "react"; import Topbar from '../H ...

Arrange the grid in a pleasing manner

I'm really struggling with this issue. In my current setup, I have a Grid container that holds two separate grids - one for a textfield and another for a checkbox. Unfortunately, I can't seem to get them to align properly. <Grid container& ...

Stop auto-scrolling to the top when triggering a getJSON request

I'm feeling really puzzled at the moment. Here is the snippet of code I am struggling with: $("#combinations").on("change", "input", function (e) { e.preventDefault(); console.log(e) var $button, $row, $group, $form, $barcode ...

Arrangement of images in an array

Here's the scenario I'm facing. https://i.stack.imgur.com/FbAfw.jpg So, I have an array of images that I want to use to create a gallery with a specific layout. I've tried using grid and playing around with :nth-child(even) and :nth-child( ...

Variations in the module pattern in JavaScript

Can someone help me understand the differences in these methods of creating a javascript "module"? I'm just looking for some clarification. A) var foo = function() { var bar = function() { console.log('test'); }; retur ...

Send the appropriate data once the response has been completed

My Express.JS server has multiple res.json responses. In order to conduct statistics, logging, and debugging, I am looking to capture the response payload using a universal hook. While I have come across the finish event res.on('finish'), I am s ...

Encountering difficulties importing an NPM library into StackBlitz

Hey there, I'm currently attempting to replicate an Angular example online but am encountering issues importing my Tabulator Library in stackblitz. I keep receiving an error when trying to import it in the hello component. import Tabulator from &apo ...

Learn how to implement a split background effect by simply clicking the SPLIT button

let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.width = window_width; canvas.height = window_height; let hit_counter = 0; // object is created using class clas ...

Is there a cutting-edge javascript/jquery tool that enables SQL-type queries on JSON datasets?

About a year ago, this question was posed on Stack Overflow. After searching extensively for answers, it seems that all the libraries I've come across have not been updated in over a year. I'm curious if anyone knows of any currently maintained l ...

Add new data to an existing array in Angular 7 without overwriting it

After clicking a button, I'm retrieving data from the WordPress API: <a (click)="initGetComments()">Get comments</a> This is the code snippet: export class AppComponent { commentsResults: CommentsItem[] = []; ...

Ways to extract text from a temporary element

Here is my HTML code: <div class="p-login-info" ng-show="loggedOut()">My text.</div> This is the corresponding JavaScript code: var e = element(by.className('p-login-info')); e.getText() .then(function(text){ var logoutText = ...

React's setState function failed to update the specified value within the set

In attempting to update the state values, I encountered an issue where the state did not get updated as expected. To troubleshoot, I included console logs at each line of code. handleFilter=(event)=> { console.log(this.state.answerStatus) // In ...

TinyMCE is deleting Bold tags in a numbered list when saving a form

I recently integrated the tinymce editor into one of my textareas, allowing users to format their text with options like bold, underline, and italic. Here is the implementation code: tinymce.init({ branding: false, statusbar: false, resize:true ...

What is the best way to showcase an image using Next.js?

I'm having a problem with displaying an image in my main component. The alt attribute is showing up, but the actual image is not appearing on the browser. Can someone please point out what I might be doing wrong? import port from "../public/port. ...