1

I have an Object which contains sub-objects as children. I need to convert it into array:

var myObj = {
    a: 5,
    b: 6,
    c: {
        a: {
            a: {
                a: 7
            }
        }
    },
    d: {
        a: {
            a: 8,
            b: 9,
            c: {
                a: 10
            }
        },
        b: 11
    }
}

like this:

myArray = [
    a: 5,
    b: 6,
    c: [
      a: [
        a: [
          a: 7
        ]
      ]
    ],
    d: [
      a: [
        a: 8,
        b: 9,
        c: [
          a: 10
        ]
      ],
      b: 11
    ]
  ];

What is the best way to achieve this?

13
  • 3
    While arrays can have properties (they are objects after all), why would you do it this way? And if you do want to do this, hint: Recursion Commented Nov 11, 2013 at 14:38
  • 1
    arrays may only have numeric keys; your desired "array" is not possible in javascript Commented Nov 11, 2013 at 14:40
  • Why do you need this? Sound like a classic XY problem meta.stackexchange.com/a/66378/162238 Commented Nov 11, 2013 at 14:40
  • because I need an array object to call it like myArray[c][a][a][a] Commented Nov 11, 2013 at 14:40
  • 4
    @zur4ik "because I need an array object to call it like myArray[c][a][a][a]" No, you don't; the square bracket notation works for accessing properties of objects as well. However, you need to pass them as strings (rather than trying to use them as the values of variables), so: myObj["c"]["a"]["a"]["a"] Commented Nov 11, 2013 at 14:42

1 Answer 1

5

As mentioned in your comments, it looks like you have an XY problem. You want X, but ask us for Y instead thinking it will help you, but in fact Y is much more difficult to solve than X.

There are two ways to access properties of an object in JavaScript:

  • obj.prop
  • obj['prop']

The difference between the two ways of accessing is that the second is more versatile, you can use some restricted keywords as property names, you can use variables to access the values, etc.

To access your nested property you can do (any option is fine):

  • myObj.c.a.a.a
  • myObj['c']['a']['a']['a']

You can even mix them: myObj.c['a'].a['a'], though it is probably more confusing, so you should avoid it.

Arrays in JS are also objects, that have some more functionality which deals with the properties with numeric names. It doesn't seem like you need any of those functionalities so you probably don't need an array.

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

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.