1

I have a list object

{
  value: 5,
  rest: {
    value: 10,
    rest: {
      value: 15,
      rest: null
    }
  }
}

that should be converted into array. I was trying to iterate through the list to take the values and push them into array.

function listToArr(obj){
let arr = []
    for (let val in object){
        arr.push(Object.values(val))
    }
    return arr
}

But I am getting [ [ 'v', 'a', 'l', 'u', 'e' ], [ 'r', 'e', 's', 't' ] ]

1
  • 3
    for..in will iterate through the object's keys, here value and rest, and a string is an array of characters, or object of pairs of index-character, which lead to your unexpeceted result above. what is your expected output in this case? Commented Dec 3, 2020 at 4:29

3 Answers 3

2

You'd need to reassign the object inside a loop and access its value property:

console.log(listToArr({ value: 5, rest: { value: 10, rest: { value: 15, rest: null } } }));

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

Since the keys are static, using Object.values or for..in doesn't accomplish anything.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice, however a nitpick would be not to mutate the argument.
The argument is not getting mutated. This would work just fine in React, for example.
Fair enough, I can see use cases for and against this lint rule: eslint.org/docs/rules/no-param-reassign
1

An ES6 style approach:

let listToArr = (obj) => obj.rest ? [obj.value, ...listToArr(obj.rest)] : [obj.value];

console.log(listToArr({ value: 5, rest: { value: 10, rest: { value: 15, rest: null } } }));

Comments

1

There's a nice recursive solution for this as well. Something like:

let a = {
  value: 5,
  rest: {
    value: 10,
    rest: {
      value: 15,
      rest: null
    }
  }
}

function listToArr(obj, arr){
    arr = arr || [];
    if (!obj) return arr;
    return listToArr(obj.rest, arr.concat(obj.value));
}
console.log(listToArr(a));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.