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' ] ]
3 Answers 3
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.
answered Dec 3, 2020 at 4:29
CertainPerformance
374k55 gold badges354 silver badges359 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Spangle
Nice, however a nitpick would be not to mutate the argument.
CertainPerformance
The argument is not getting mutated. This would work just fine in React, for example.
Spangle
Fair enough, I can see use cases for and against this lint rule: eslint.org/docs/rules/no-param-reassign
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 } } }));
answered Dec 3, 2020 at 4:40
Zze
18.9k14 gold badges95 silver badges125 bronze badges
Comments
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));
answered Dec 3, 2020 at 4:36
xdhmoore
10.2k12 gold badges57 silver badges103 bronze badges
Comments
lang-js
for..inwill iterate through the object's keys, herevalueandrest, 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?