Reputation: 6254
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?
Upvotes: 1
Views: 942
Reputation: 27823
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.
Upvotes: 5