Display the elements of an object in a sequential order

Display the elements of an object. Ex.

const employees = {
    "Jacobs": ["Emiel", "Svjetlana", "Ivanna"],
    "Ivanna": ["Michael", "Lawson"],
    "Emiel": ["John", "Ruby"],    
    "Lawson": [],
    "Michael": ["Lindsay", "Ferguson"],
    "Ferguson": []
}

In the example above, let's assume that "Jacobs" is the parent of "Emiel", "Svjetlana", and "Ivanna". We need to print the sequence "Jacobs", "Emiel", "Svjetlana", "Ivanna", which means first the parent followed by the children.

Output should be: 
"Jacobs" 
"Emiel"
"Svjetlana"
"Ivanna"
"Emiel"
"John"
"Ruby"
"Ivanna"
"Michael"
"Lawson"
"Michael"
"Lindsay"
"Ferguson"

Answer №1

const employees = {
  "Jacobs": ["Emiel", "Svjetlana", "Ivanna"],
  "Ivanna": ["Michael", "Lawson"],
  "Emiel": ["John", "Ruby"],
  "Lawson": [],
  "Michael": ["Lindsay", "Ferguson"],
  "Ferguson": []
}

const empArr = Object.entries(employees)
const empParents = Object.keys(employees)
const firstChildren = empArr.map(arr =>
  arr[1][0]
)
let remainingParents = empParents.filter(item => item !== empParents[0]);

const result = empArr.reduce((acc) => {
  const firstChild = acc.firstChild;
  // if has children add it and its children
  if (employees[firstChild] ?.length > 0) {
    remainingParents = remainingParents.filter(item => item !== firstChild);
    return {
      res: [...acc.res, firstChild, ...employees[firstChild]],
      firstChild: employees[firstChild][0]
    }
  } else {
    // if has no children move on to the item which has not already been added and is not the first child of any item
    const newParent = remainingParents.find(pName => !firstChildren.includes(pName))
    remainingParents = remainingParents.filter(item => item !== newParent)
    if (employees[newParent]) {
      const newParentData = employees[newParent].length > 0 ? [newParent, ...employees[newParent]] : []
      const firstChildData = typeof employees[firstChild] !== "undefined" ? [firstChild] : []
      const newFirstChild = employees[newParent][0];
      return {
        res: [...acc.res, ...newParentData, ...firstChildData],
        firstChild: newFirstChild
      }
    } else
      return acc
  }
}, {
  res: [
    empParents[0], ...employees[empParents[0]]
  ],
  firstChild: employees[empParents[0]][0]
})
result.res.map(item=>console.log(`"${item}"`))

Answer №2

Below is the code snippet you can utilize:

const employees = {
    "Smith": ["Alice", "Bob", "Charlie"],
    "Alice": ["David", "Emma"],
    "Bob": ["Frank"],
    "Charlie": [],
    "David": ["Grace", "Hannah"],
    "Hannah": []
}

function display(obj) {
    for(let key in obj) {
        console.log(key);
        obj[key].forEach(value => console.log(value));
    }
}

display(employees);

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

How can I retrieve the name of the upcoming middleware function in Express.JS?

Hey there, I'm currently facing a challenge with retrieving the names of middleware functions in a specific request route. Let's consider the code snippet below as an example: const authorizeRoute = (req,res,next) => { let nextFunctionName = ...

Creating a JSON hierarchy from an adjacency list

I am currently working with adjacency data that includes ID's and Parent ID's. My goal is to convert this data into hierarchical data by creating nested JSON structures. While I have managed to make it work, I encountered an issue when dealing ...

Importing classes in ECMAScript 6 does not work properly, causing issues when running scripts

I am currently learning Selenium Webdriver. I am facing an issue where I can't run a script with imported classes, but I am able to run it without classes using import functions only. To execute it, I use babel-cli in the following manner: node ./babe ...

Send the checkbox value using ajax, jquery, and php

Hey everyone, I'm facing an issue and need some help. I am trying to send the value of a checkbox via AJAX to a PHP file. My question: I want to pass the checkbox value regardless of whether it is checked or not. If it is checked, then the value "tr ...

Locate a specific value within an array of objects and display it

Data : const areas = [ { "ID":"4131", "RID":"f1438b", "Name":"City" }, { "ID":"6266", "RID":& ...

What could be causing the undefined status of this length function?

I need to determine the length of seconds. If the second is only one character long, I want to add a 0 in front of it. Otherwise, no action is needed. Below is my code: <p>Click the button to show the current number of seconds.</p> <p id= ...

Synchronizing multiple file changes simultaneously in Node.js

I have a small development server set up specifically for writing missing translations into files. app.post('/locales/add/:language/:namespace', async (req, res) => { const { language, namespace } = req.params // Utilizing fs.promises l ...

Chrome and Firefox provide excellent compatibility for running JavaScript, whereas Safari may encounter some issues. Opera's performance with JavaScript can be quirky

Disclaimer: I'm new to web design and development. I have encountered an issue with posting information from a form built on CodeIgniter using jQuery. The form posts successfully in Chrome and Firefox, with the current page automatically reloading. H ...

Chip input component in React

I've recently upgraded to React 17 and encountered an issue with chip input fields like material-ui-chip-input not working properly. I've tried various npm packages, but none of them seem to be compatible with React version 17. Does anyone know ...

Rotating an image as it approaches the footer: a step-by-step guide

I'm trying to add a navigation arrow on my website that will rotate to point to the top when it reaches the footer. When clicked on, it should scroll back up to the top. The arrow already has a scrolling effect, but I need help figuring out how to m ...

The lifecycle of a React state in a filtering component

Seeking guidance on handling state updates in a component designed for filtering purposes (such as selecting dates, min/max values, etc). My current setup is as follows: onMinDateChange(minDate) { this.setState({minDate}); }, onMaxDateChange(maxDate) ...

Saving data for editing on a Laravel page can be achieved by leveraging the powerful features

I have implemented my create page using vue.js. I called the vue.js file using a component. Now, for the edit page, I followed the same procedure by calling the vue component in the blade. However, I am unsure how to save data for the edit page. Can anyone ...

Turn off the feature that prohibits the use of variables before they are

I'm struggling to disable this setting in my tsconfig file. The TS documentation doesn't seem to have any information about how to do it. no-use-before-declare I'm facing an issue where my test stub data objects are interfering with each ot ...

execute javascript code after loading ajax content

Although this question may have been asked before, I am completely unfamiliar with the subject and unable to apply the existing answers. Despite following tutorials for every script on my page, I have encountered a problem. Specifically, I have a section w ...

Obtain an Instance of a Class Using a Decorator

Delving deep into the world of decorators, I stumbled upon some fascinating ideas for incorporating them into my reflux implementation. My concept involves tagging a store's class method with an action, so that whenever that action is triggered, it au ...

Switch Tabs with Dropdown Selection

I came across a website with a similar feature, but I am interested in using a dropdown menu instead of a button or link. Check out this webpage for reference The problem seems to be related to this line of code: onchange="$('#'+$this).tri ...

Leveraging window.hash and the power of WordPress htaccess

I have a Wordpress website where I am using Ajax to display posts in a specific section. I am currently having Javascript add the hash tag like this: window.location.hash = id; Everything is working as expected. For instance, it changes the URL to www.my ...

Error: Unable to access the 'nom_gr' property of null - encountered in Chrome

<ion-col col-9 class="sildes"> <ion-slides slidesPerView="{{nbPerPage}}" spaceBetween="5"> <ion-slide *ngFor="let slide of lesClassrooms; let i = index" (click)="saveCurrentSlide(i)"> ...

What is the method for accessing a local XML file with $.ajax?

Currently, I am working on developing a Firefox extension that requires reading a local XML file. However, I have encountered an issue with using $.ajax to read the file. Here is a snippet of my code: $.ajax({ type: "GET", url: "file:/// ...

What is the best way to implement a promise function in this scenario using JavaScript?

I am currently working on an app using AngularJS and the MediaFire JavaScript SDK to perform various tasks. One specific task I am struggling with is creating a folder during an upload process, which returns a 'folderkey'. I would like to use .t ...