Creating a new attribute within a JavaScript object by utilizing the properties of its sibling elements

Imagine a scenario where you have a complex array of objects structured like this:

[
  {
    "title": "Fundamentals",
    "order": 1,
    "lessonRef": "fundamentals",
    "children": [
      {
        "title": "History",
        "order": 1,
        "lessonRef": "history",
        "children": []
      },
      {
        "title": "NEW NODE 1",
        "lessonRef": "NEW NODE 1 STUB",
        "children": []
      },
      {
        "title": "Math",
        "order": 2,
        "lessonRef": "math",
        "children": []
      },
      {
        "title": "NEW NODE 2",
        "lessonRef": "NEW NODE 2 STUB",
        "children": []
      }
      {
        "title": "Geography",
        "order": 3,
        "lessonRef": "geography",
        "children": []
      }
    ]
  },
  {
    "title": "Basics",
    "order": 2,
    "lessonRef": "basics",
    "children": []
  }
]

How can you:

  1. Sequentially go through each node,
  2. Detect any new node that does not have the order field and assign it the next number depending on its position in the array,
  3. Subsequently, increment the order of every existing sibling after it while also
  4. Considering any other newly added nodes that come after it?

I am seeking a lodash method to help me initiate the process before delving into pure javascript.

UPDATE: I have shared my solution -- note that the order of elements in the array is set, but the question will be expanded to address scenarios where the order is not predefined.

Answer №1

if this is what you wish to accomplish:

let yourArrayData = yourDataArr
let arr1 = []


//begin with fixing children
_.each(yourArrayData, function(element) {
    if(element.children) element.chilren = adjustArr(children)
    arr1.push(element)
})


//adjust your array
yourArrayData = adjustArr(arr1)


//fix the function
function adjustArr(arr) {

    let result = []
    let previousOrder

    _.each(arr, function(element) {


        let currentOrder = element.order

        if(!currentOrder) {
            element.order = previousOrder?previousOrder + 1:1
            previousOrder = element.order + 0
        }
        result.push(element)

    })

    return result

}

//alternatively, this might be what you are looking for
function adjustArrAlt(arr) {

    let result = []
    let order = 1

    _.each(arr, function(element) {

        element.order =  order + 0
        result.push(element)
        order ++

    })

    return result

}

Answer №2

Following the advice of @jfriend00, I iterated through each element in the array recursively and assigned a specific order based on its index:

function updateElementOrder(array){
  return _.map(array, function (value, index) {
    value.order = index + 1;
    if(value.children.length > 0){
      value.children = updateElementOrder(value.children);
    }
    return value;
  });  
}
$scope.array = updateElementOrder($scope.array);

In my scenario, the order of the array is predetermined, but I pose the question of how to handle cases where the order is not predefined.

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

Tips for sending a JavaScript variable through an AJAX URL

I currently have a variable defined like this: var myip; I need to include this variable in the following URL: $.ajax('http://api.ipstack.com/**[myip]**?access_key=mykey') Manually replacing [myip] with my IP address works fine, but I am loo ...

Javascript adds a comma after every postback event

This particular JavaScript code I am incorporating helps in expanding and collapsing nested grid views. <script type="text/javascript"> $("[src*=plus]").live("click", function () { $(this).closest("tr").after("<tr><td></td ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

Attempting to extract data from a text document and organize it into an array

Having trouble splitting a text file and extracting the information into an array to be able to select and print a specific index. The text file has the following format: X;25 Y;15 The goal is to split the file to print X 25 and Y 15, or print each item ...

Tips on adjusting a standard CSS layout with JavaScript and jQuery to generate a unique ID for the updated style

My CSS contains IDs that look like this: <style> .HIDE-DISPLAY-k { background-color: orange; position: fixed; width: 100%; height: 100%; top: 10px; bottom: 0px; left: 10px; right: 0px; overflow: hidden; } #SHOW- ...

HeatMap Visualizations Data

I have a HeatMap calendar project () where I am attempting to populate it with dynamic data. My approach involves extracting various dates from a file and converting them into milliseconds in order to create the necessary key-value pair for the calendar. ...

Animation of active chat list items on Whatsapp

Has anyone figured out a simple method to create an animation like the one in Whatsapp? For example, when you are on a chat screen and go back to the chat list, have you noticed how an active element is briefly highlighted in gray (to indicate which chat ...

Is it possible to verify if the provided form input variable exists within an array? Can anyone point out any oversights?

Feeling a bit lost here, not sure what I've missed. Any help would be greatly appreciated as my calculations never seem to come out right. function validateZip(){ var zipCode = $("input[name='zipCode']").val(); var redRiverHondaZips = ...

Having trouble with my ReactJS application where click interactions are functioning properly on the header but not on my content

Objective: Implement an iframe displaying a YouTube video with play/pause functionality for users. Issue: Unable to interact with main content, but works correctly when placed in Navigation or Footer components. Attempted Solutions: Explored various de ...

Issues with jQuery Ajax functionality in Rails application not achieving successful completion

When a card is moved onto another stack, an Ajax call is triggered twice. This only happens when there are multiple stacks. However, if the cards are rearranged within the same stack, the call is triggered only once. The Ajax call sends an array of IDs fo ...

Create a dynamic image showcase using PHP or JavaScript

So I have a large collection of car photos organized in a structure similar to this (this is just a fictional example to illustrate my idea): Cars > Audi > Sports cars > '5 pictures' Cars > Audi > Family cars > '3 pictur ...

Exploring Ternary Functions within an Associative Array in PHP

I am curious about the possibility and potential lack of side effects when assigning associative array elements using a ternary function in PHP. Instead of the traditional method: $second_element = $test ? "tistrue" : "tisfalse"; echo build_assignment_pa ...

DataTables prioritizes sorting strings over numerical values

I am currently utilizing jquery.datatables to display numbers in columns within datatables. The numbers are formatted with spaces between thousands units (e.g. 123 456 789). However, this formatting causes the sorting to treat the numbers as strings rather ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

Leveraging Next.js 'useClient' in conjunction with server component (global)

Hello there! I'm trying to achieve a 50% opacity effect on my Gallery when the search bar is in use. However, I'm facing challenges using 'use client' with the glob library. Here's the code snippet: app/page.tsx "use client&qu ...

How to retrieve the value of an observable from a regular JavaScript array in Knockout JS?

Context In my project, I am working with a plain JavaScript array that starts off empty but gets populated with Knockout observables later on. These values are numbers and I need to compare them with values in another Knockout observable array. The issue ...

Issue with ThemeManager in Material UI & React: Constructor is not valid

Currently, I am integrating Material UI into a small React application, but I suspect that the tutorial I am following is outdated and relies on an older version of Material UI. The error _materialUi2.default.Styles.ThemeManager is not a constructor keeps ...

Can you recommend any open source projects with exceptionally well-written Jasmine or Jasmine-Jquery tests?

Currently, I am in the process of learning how to test a new jquery plugin that I plan to develop. I'm curious if there are any notable Github projects like Jasmine or Jasmine-jquery with impressively crafted Jasmine tests that I could explore for in ...

Obtaining the complete JSON array in string format

I am currently using Fine Uploader to pass parameters in this way callbacks: { onSubmit: function(id, fileName) { this.setParams({ a: 'adm', b: '126', c: { fileID: id, ...

I'm having trouble with Material Design Slide Toggle as it lacks event.StopPropagation functionality. Any suggestions on what alternative I

When working with the Slide Toggle in Material Design, I noticed that it does not have a stopPropagation event. This is because the "MdSlideToggle.prototype._onChangeEvent" already includes a call to stopPropagation. So, what should be used instead? <m ...