skip to Main Content
const list = {"value":10,"rest":{"value":20,"rest":null}};

function list_to_array(list) {
  arr = [];
  for (const property in list) {
    if (property == "value") {
      arr.push(property);
    } else if (property == "rest") {
      for (const property in rest) {
        arr.push(property);
      }
    }
  }
}
console.log(JSON.stringify(list_to_array(x)));

but I get the error Uncaught ReferenceError ReferenceError: rest is not defined how can I iterate in the rest object ? or how would you do this function

this functions transform a list to an array

2

Answers


  1. This line x = array_to_list([10, 20]); could be x = list_to_array([10, 20]);

    Login or Signup to reply.
  2. You need to use a recursion here, if you the property is "rest". In addition to get the value use 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])); // call list_to_array on the rest
        }
      }
      
      return arr; // return the arr
    }
    
    const list = {"value":10,"rest":{"value":20,"rest":null}};
    
    const result = list_to_array(list);
    
    console.log(JSON.stringify(result));

    However, you can shorten this recursion easily:

    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));

    A simpler solution would be to use a while loop, and take the rest property value on 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 arr
    }
    
    const list = {"value":10,"rest":{"value":20,"rest":null}};
    
    const result = list_to_array(list);
    
    console.log(JSON.stringify(result));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search