let object = {
name: 'color',
values: [
{
id: 'color-red',
value: 'red'
},
{
id: 'color-blue',
value: 'blue'
}
],
labels: {
one: 'one label',
two: 'two label'
}
};
let array = [
{
id: 0,
_key: 'name',
_value: 'color',
type: 'string',
childIds: [
],
},
{
id: 1,
_key: 'values',
_value: false,
type: 'array',
childIds: [
2,
3
],
},
{
id: 2,
_key: false,
_value: false,
type: 'object',
childIds: [
4,
5
],
},
{
id: 3,
_key: false,
_value: false,
type: 'object',
childIds: [
6,
7
],
},
{
id: 4,
_key: 'id',
_value: 'color-red',
type: 'string',
childIds: [
],
},
{
id: 5,
_key: 'value',
_value: 'red',
type: 'string',
childIds: [
],
},
{
id: 8,
_key: 'labels',
_value: false,
type: object,
childIds: [
9,
10
],
},
{
id: 9,
_key: 'one',
_value: 'one-label',
type: 'string',
childIds: [
],
},
{
id: 10,
_key: 'two',
_value: 'two-label',
type: 'string',
childIds: [
],
}
];
this.renderTree(object, []);
renderTree(object, array, parent = '') {
if(!Array.isArray(object)) {
for( let key in object) {
if(typeof object[key] === 'object') {
if(!Array.isArray(object[key])) {
array.push({
id: array.length,
_key: key,
_value: false,
type: 'object',
childIds: [],
});
this.renderTree(object[key], array, array.length - 1);
} else {
array.push({
id: array.length,
_key: key,
_value: false,
type: 'array',
childIds: [],
});
this.renderTree(object[key], array, array.length - 1);
}
} else {
array.push({
id: array.length,
_key: key,
_value: object[key],
type: 'string',
childIds: [],
});
if(parent) {
array[parent].childIds.push(array.length - 1);
}
}
}
} else {
let index, len;
for(index = 0, len = object.length; index < len; ++index) {
let element = object[index];
if(typeof element === 'object') {
array.push({
id: array.length,
_key: false,
_value: false,
type: 'object',
childIds: [],
});
array[parent].childIds.push(array.length - 1);
this.renderTree(element, array, array.length - 1);
}
}
}
}