3

This is my array. I have multiple objects in it, some having values undefined.

var array = [
    { 0: undefined, 1: 32, 2: "four" },
    { 0: undefined, 1: undefined, 2: "three" },
    { 0: undefined, 1: 24, 2: "two" },
    { 0: 14, 1: 24, 2: "five" },
    { 0: 10, 1: 21, 2: "one" },
]

I want to check if the array objects have undefined value and if they have any undefined value the next objects should be appended.

Example In the first element {0: undefined, 1: 32, 2: "four"} I have 0:undefined the second {0: undefined, 1: undefined, 2: "three"} element should replace this and new object should form which is {0: {0: undefined, 1: undefined, 2: "three"}, 1: 32, 2: "four"}.

I know the Array.forEach can do this. I can do if it was array like by using Array.splice() and Array.lastIndexOf(). Like first search from right side or last undefined value and append the next array in it then do it again again.

The final array must be like :

{
  0: {
    0: {
      0: 10,
      1: 21,
      2: "one"
    },
    1: {
      0: {
        0: 14,
        1: 24,
        2: "five"
      },
      1: 24,
      2: "two"
    },
    2: "three"
  },
  1: 32,
  2: "four"
}
Nur
  • 2,361
  • 2
  • 16
  • 34
Coding
  • 33
  • 5
  • This can be done like first search from the last side if it has undefined value then append it then again search from right side of the new object if it has then append. – Coding Jun 15 '21 at 04:12
  • @Barmar I did i don't know how to do convert it objects when I convert it becomes messy – Coding Jun 15 '21 at 04:46
  • You can use `if (Object.values(element).some(el => el === undefined))` to check if there are any `undefined` values in the current element of the loop. I hope that helps you get started. – Barmar Jun 15 '21 at 04:50

1 Answers1

4

You can use a recursion function to do so, code:

var array = [
    { 0: undefined, 1: 32, 2: "four" },
    { 0: undefined, 1: undefined, 2: "three" },
    { 0: undefined, 1: 24, 2: "two" },
    { 0: 14, 1: 24, 2: "five" },
    { 0: 10, 1: 21, 2: "one" }
]

function tree(array) {
    let obj = array.shift();

    for (let [key, value] of Object.entries(obj).reverse())
        if (value === undefined)
            obj[key] = tree(array);

    return obj;
}

console.log(tree(array));
Nur
  • 2,361
  • 2
  • 16
  • 34