Transform a series of items into an array

I have a task where I need to create a function that takes a list as an argument and returns its elements in an array format. For instance, if the input is:

{value: 1, rest: {value: 2, rest: null}}

Then, the expected output should be:

[1, 2]

This is my attempted solution:

function listToArray(list){
  var arr = [];
    for (var node = list; node; node = node.rest) {
        arr.push(node.value);

    }
  return arr;

}
console.log(listToArray({value: 1, rest: {value: 2, rest: null}}));

The actual output I'm getting is:

[{value: 2, rest: null}, {
value:  1
rest:   {value: 2, rest: null}
}]

If anyone has suggestions on how to fix this issue, please let me know. Thank you!

Answer №1

Don't forget to include the .value in your node variable.

function convertListToArray(list){
  var array = [];
    for (var node = list; node; node = node.rest) {
        array.unshift(node.value);
    }
  return array;
}
console.log(convertListToArray({value: 1, rest: {value: 2, rest: null}}));

Consider using push instead of unshift.

Answer №2

Recursion can be utilized to extract all the values from nested objects.

var data = {value: 1, next: {value: 2, next: null}};
var extractedValues = extractValues(data, 'value', 'next');

console.log(extractedValues);

function extractValues(obj, valueKey, targetKey) {
  return extractValuesRecursive(obj, valueKey, targetKey, []);
}

function extractValuesRecursive(obj, valueKey, targetKey, list) {
  if (isObject(obj)) {
    list.push(obj[valueKey]);
    extractValuesRecursive(obj[targetKey], valueKey, targetKey, list)
  }
  return list;
}

function isObject(obj) {
  return obj !== null && typeof obj === 'object';
}
.as-console-wrapper {
  top: 0;
  max-height: 100% !important;
}


A fun exercise in concise coding. ;)

let data  = {value: 1, next: {value: 2, next: null}},
    extractedValues = extractValues(data, 'value', 'next');

console.log(extractedValues);

function extractValues(o, v, t, l) {
  return o ? extractValues(o[t], v, t, (l||[]).concat(o[v])) : (l||[])
}
.as-console-wrapper {
  top: 0;
  max-height: 100% !important;
}

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 mechanism by which callback responses are handled in Express/Node?

I wrote an async function that retrieves data from a file and uses a callback function to process the result: static fetchAll(callback){ fs.readFile(pathToDB, (err, fileContent) => { if(err){ callback([]); ...

Troubleshooting a Node.js server issue with a two-dimensional array

I am currently facing an issue with submitting a form that contains two-dimensional array fields on a post request in node.js. The problem lies in the fact that the server side is receiving a one-dimensional array with all the values combined. Below is an ...

Looking to incorporate React Canary in raw HTML? Or perhaps interested in adding react-dom/client into your project?

Due to certain undisclosed reasons, I am developing a React application without the use of bundlers like webpack. Instead, I simply include React and ReactDOM using <script> tags in my index.html, fetching them from a CDN: https://cdnjs.cloudflare.co ...

Adding and sorting div elements from an external HTML file

Greetings everyone, I have recently delved into the world of coding and am currently working on a project for my course to streamline access to information and data in my daily life. So far, I have created a single HTML file and two additional external HT ...

What is the mechanism by which the callback methods of the $http service inform Angular of a change in the model?

Consider the AngularJS controller provided below: function PhoneListCtrl($scope, $http) { $scope.phones = {}; $http.get('phones/phones.json').success(function(data) { $scope.phones = data.splice(0, 5); }); $scope.orderProp = ...

Steps for activating mouse dragging in a div that supports drag and drop functionality

I have a div containing multiple elements, and I need the ability to drag and drop the entire div with the attribute draggable=true. However, one of the elements in the div is a bar graph that allows users to select a specific range by dragging their mouse ...

Do API applications require a session to function properly?

I am in the process of developing an API and I am unsure whether I should implement express-session or a similar tool to handle sessions. app.use(expressSession({ secret: 'Something' }); Moreover, I have been blocking CORS. Is this measure suf ...

How can I remove the most recently added div using JavaScript?

Currently, I am expanding my knowledge in Javascript and encountered a problem. There is a function set up to add boxes every time I click "Add Data". I can continue adding multiple boxes this way, but I need assistance with implementing a button labeled " ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

Axios continues to encounter the issue of downloading a faulty PDF file

Every time I attempt to download a PDF file to the client side using axios, it ends up corrupted. In my MERN stack webapp, a user can click a button to initiate the download of a PDF file. This button triggers an axios GET request to the Node.js web server ...

Implementing popup alert for multiple tabs when Javascript session times out

I have implemented javascript setInterval() to monitor user idle time and display a popup alert prior to automatic logout. However, it seems to be functioning correctly only in single tabs. Here is the code snippet: localStorage.removeItem("idleTimeValue ...

Iterate over a JSON object to calculate the total sum of values based on distinct nested properties

Here is a JSON object that contains cost and author information. I am working on this in Express.js and using Underscore. [ { "Cost": 250, "author": { "id": "2", "name": "Joe", "workId": "5" } }, { ...

The browser is displaying the scene, but the Three.js Geometry is not visible

After following a tutorial and successfully getting the entire scene to work within the body tag, I decided to move it inside a div. However, now only the scene itself is rendered. Despite not receiving any errors and ensuring everything is accessible thro ...

The $interval cancellation in AngularJS is not functioning as expected, and neither the onDestroy nor stateChangeSuccess events are working as

Below is a snippet of code I wrote to set up an interval that should be canceled when leaving the state, but it's not working as expected. var init = function () { $translatePartialLoader.addPart("app/bottling/palletTnT/palletTnT.grid"); ...

Is there a way to automatically assign a default value to radio buttons when the page is loaded?

Working with OpenERP 7, I encountered a problem with two radio buttons that should change the values of a table. After creating an event that triggers a Python function to execute an SQL query, I found that upon reloading the page, the radio buttons revert ...

What is the preferred method for storing JSON data - using a single data attribute or multiple separate data attributes?

When it comes to storing multiple data attributes for a single DOM element, the question arises: Is it better to have a single data attribute containing JSON data, or is it more efficient to have separate data attributes for each value needed? <select ...

Storing values from a PHP array into a MySQL table as separate rows

My goal is to insert multiple rows into a MySQL table using PHP arrays. I have managed to get the values in pairs of brackets, but when I attempt to insert them, I encounter an error message stating "Error: Column count doesn't match value count at ro ...

Add multiple checkboxes in a dropdown menu to save in a MySQL database

I have a register.php and I'm trying to insert the data into users table. The problem I have is with "languages" field - I've created a dropdown list with multiple checkboxs. I want the user of course to be able to insert to his profile more tha ...

"Enhance your website with autocomplete feature using the power of jQuery 1.4.2 and jQuery UI 1

Struggling to make jQuery autocomplete work. Despite searching for examples, most seem outdated. Modeled after a good example from the jQuery UI site but still can't get it to display data. My JSON data source is accessed via URL. [{ "pk": 1, "mo ...

How to retrieve the ID of a table column using jQuery in HTML

I am facing an issue with a HTML table that consists of only one row and one column: <table id="backlog"> <colgroup> <col width="200"></colgroup> <tbody> <tr><td id="91" tabindex="0" class="mark">BackLog&l ...