I have an array [1, 2, 3]
and I want to transfer it to object with nested parent-child objects's series like this :
{ value: 1, rest: { value: 2, rest: { value: 3, rest: null } }
If I have an array [1, 2, 3, 4]
the result will be like this :
{ value: 1, rest: { value: 2, rest: { value: 3, rest: { value:4, rest:null } }
The best effort of me is this snippet of code :
const arrayToList = (array) => {
let list = { value: null, rest: null };
for (let e of array) {
array.indexOf(e) === 0 && (list.value = e);
array.indexOf(e) >= 1 && (list.rest = { value: e });
}
return list;
};
console.log(arrayToList([1, 2, 3]));
To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.
const obj = { code: "AA", sub: { code: "BB", sub: { code: "CC", sub: { code: "DD", sub: { code: "EE", sub: {} } } } } }; Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple. We can solve this problem using a recursive approach.
After creating a JavaScript nested array, you can use the “push()” and “splice()” method for adding elements, “for loop” and “forEach()” method to iterate over the elements of the inner arrays, “flat()” method for reducing the dimensionality, and “pop()” method to delete sub-arrays or their elements from the nested ...
You can use reduceRight
like so:
let obj = arr.reduceRight((rest, value) => ({ value, rest }), null);
It starts building the object from the inside out; it starts by creating the innermost object and then it uses that object as the rest
property for the next outer object and so on until there are no more items in the array.
Demo:
let obj = [1, 2, 3, 4].reduceRight((rest, value) => ({ value, rest }), null);
console.log(obj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With