Transforming a list into an array using JavaScript

This specific function serves to convert a list into an array:

const myList = {"value":10,"rest":{"value":20,"rest":null}};

function convertListToArray(list) {
  let arr = [];
  for (const prop in list) {
    if (prop == "value") {
      arr.push(prop);
    } else if (prop == "rest") {
      for (const innerProp in rest) {
        arr.push(innerProp);
      }
    }
  }
}
console.log(JSON.stringify(convertListToArray(myList)));

However, encountering the error

Uncaught ReferenceError ReferenceError: rest is not defined

What is the best way to iterate through the rest object? Or can you propose an alternative approach to rewrite this function?

Answer №1

To implement this, it is necessary to utilize recursion specifically for the "rest" property. To access the value, make use of list[property]:

function list_to_array(list) {
  const arr = [];
  
  for (const property in list) {
    if (property == "value") {
      arr.push(list[property]);
    } else if (property == "rest") {
      arr.push(...list_to_array(list[property])); // execute list_to_array recursively on the rest
    }
  }
  
  return arr; // return the array
}

const list = {"value":10,"rest":{"value":20,"rest":null}};

const result = list_to_array(list);

console.log(JSON.stringify(result));

Alternatively, you can simplify the recursive process by consistently adding the value. If there is a "rest" property present, call the function with the "rest" and the current array "arr". If no "rest" exists, simply return "arr":

function list_to_array({ value, rest } = {}, arr = []) {
  arr.push(value);
  return rest ? list_to_array(rest, arr) : arr;
}

const list = {"value":10,"rest":{"value":20,"rest":null}};

const result = list_to_array(list);

console.log(JSON.stringify(result));

An easier approach would involve utilizing a "while" loop to extract the value of the "rest" property during each iteration:

function list_to_array(list) {
  const arr = [];
  let current = list;
  
  do {
    arr.push(current?.value);
  } while(current = current?.rest);
  
  return arr; // return the array
}

const list = {"value":10,"rest":{"value":20,"rest":null}};

const result = list_to_array(list);

console.log(JSON.stringify(result));

Answer №2

It is advisable to steer clear of using recursion in this case, especially when dealing with large lists as it may easily cause a stack overflow. A straightforward while loop would be more suitable:

function convert_list_to_array(list) {
  const arr = [list.value];
  while(list = list.rest) arr.push(list.value);
  return arr;
}

const list = {"value":10,"rest":{"value":20,"rest":null}};

const result = convert_list_to_array(list);

console.log(...result);

Answer №3

Here's a helpful tip: instead of using x = array_to_list([10, 20]);, you can use x = list_to_array([10, 20]); for better results.

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

Vuetify's <v-text-field> feature automatically clears the input after selecting a result from Google Maps autocomplete

A dilemma I'm facing is with a page that has a <v-text-field> containing GoogleMaps autocomplete. The problem arises when Vuetify clears the input once an address is selected by the user. I have discovered that this complication is connected to ...

Creating a straightforward Theme Changer feature using Vue.js

Check out this tutorial for creating a simple Dark/Light theme switcher using Tailwind CSS. This tutorial utilizes vanilla JS and only requires a single app.js file. If I want to incorporate this into a Vue project, should I simply paste the code into ~/s ...

Unexpected behavior observed in while loop with dual conditions

To break the while loop, I need two conditions to be met - res must not be undefined, which only happens when the status code is 200, and obj.owner needs to match a specific value I have set. Since it takes a few seconds for the owner on that page to updat ...

Adjust the visibility of components depending on the width of the screen

In my project, I have a Wrapper component that houses filters. This component becomes visible when the openMobileFilters() function is called and disappears when closeMobileFilters() is triggered. The Wrapper component occupies the entire page, and I want ...

Utilize the power of Nuxt and Vue 3 to create sortable columns in a table, with the ability to only change the icons on the sorted column

I am facing a challenge with my sortable table icons. Whenever I click on an icon to sort a column, all the other icons also change direction. I understand that this is happening because I am toggling the visibility of icons based on the currentSortDir sta ...

I require JSON formatting containing the necessary values for integration with the Flot Chart plugin

I need assistance with retrieving data from a mysql database to populate a chart using the Flot plugin. According to the documentation, the data format should be an array of dots: [ [x1, y1], [x2, y2], ... ]. In my scenario, I am looking to extract date an ...

Immense trade adhesive navigation bar menu

Currently, I am in the process of enhancing a big commerce website and aiming to implement a sticky menu on scroll. I attempted to use bootstrap along with CSS to achieve this functionality, however, encountered some issues. Below is the snippet of code I ...

Tips for showcasing an image using the ajax success callback?

I have implemented an AJAX function with dynamic value retrieval to display images based on the returned value. In the success function, I aim to showcase the image within a specific div element. var num=document.getElementById('number').value; ...

Obtaining a cookie in Vue.js independently: a step-by-step guide

After setting a cookie using laravel, I'm looking to retrieve it in vue.js without relying on or installing any external dependencies. Can anyone please suggest a way to achieve this without extra tools? Your guidance would be greatly appreciated! ...

What is the best way to retrieve the output of MongoDB's collection.aggregate() within a NodeJS callback function?

In my database, I have a users collection with the following data: { "_id" : ObjectId("5b29ba37cd0b1726068731c3"), "name" : "Gym Dog", "profilePicUrl" : "https://i.imgur.com/mPStaKV.png", "totalProgress" : { "goal" : 300, "progress ...

Tips for combining all filtered items into a single state variable

I have an array of objects containing user data stored in a state variable and a table where these users are displayed. There is a search field where users can type names to search through the list. My question is, when a user types a name, I want to sea ...

Looking for assistance with customizing my jQuery input styling

Check out this simplified version of the code: $(document).ready(function() { var $checkbox = $('input[type="checkbox"]'); $checkbox.wrap('<div class="stylecheck-container" style="display: inline" />').addClass('style ...

Adding a half circle connector in HTML can be accomplished by using SVG (Scal

My task is to replicate the construction shown in this image: https://i.sstatic.net/kaRMO.png I have written the entire code but I am unsure how to include a half circle next to the full circle and connect it with a line connector. Here is my code: .ps- ...

The issue of an endless loop being caused by utilizing HTML input as a function parameter

I created a JavaScript prime factor calculator that I'm trying to integrate into my website. I want users to be able to input their own number, but whenever the input is submitted, it leads to an infinite loop. After investigation, I found that the is ...

The React development server is experiencing issues on the Apple MacBook Pro M1

Currently, I am using an Apple MacBook Pro M1. When attempting to start the react development server with react-scripts start, it hangs and fails to start the server altogether. I also experimented with a new sample app created through create-react-app cl ...

What is the best way to access document identifiers in a Firestore Database?

I am completely new to working with Angular, Firestore, and Firebase. Currently, I have a component set up that successfully retrieves all my hero documents. I was able to display their names in a list. However, my next goal is to retrieve the unique ID f ...

What is causing the Link component in react-router-dom to not accept the className props?

Here's a customized component called PageLink: export const PageLink: React.FC<IProps> = ({ id, question, searchBy }) => { return ( <Link to={{pathname: `results/${id}`, search: `?sortBy=${searchBy}`}} className={styles.PageLink}> ...

Vue JS encountering issues in rendering method's returned data on DOM

HTML Template <div class="item" v-for="n, index in teamRoster"> <span> {{ getFantasyScore(n.personId) }} </span> </div> Function getFantasyScore(playerId) { if(playerId) { axios.get(config.NBLAPI + config.API.PLAYE ...

How can I locate an element within the body of an if statement?

I am working on a simple JavaScript (jQuery library) if statement to check for the presence of a div element with the class 'video' on the page. If it finds the element, the variable 'arrows' is set to true, otherwise it is set to false ...

Tips for accessing information from a FOR loop within DIV tags

Let's explore the following code snippet: Here is the HTML generated: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Website ...