Answer the question
In order to leave comments, you need to log in
How to check the existence of properties on a dynamic object in javascript and create them if they do not exist?
Friends, I'm trying to parse data on a node and build a tree. Lines of the form Site1\Category1\Title1 arrive in dataChapter, it is necessary to build a tree of the form from these lines:
root = {
name: 'Сайт1',
children: [{
name: 'Рубрика1',
children: [{
name: 'Заголовок1'
}]
}]
}
...
var chapters = dataChapter.split('\\');
var root = {}
var tree_pointer = 'root';
for(var j=0, jlen = chapters.length; j < jlen; j++){
if(!tree_pointer.hasOwnProperty("name")) {
tree_pointer['name'] = chapters[j];
}
tree_pointer += '.children';
}
...
Answer the question
In order to leave comments, you need to log in
function makeTree(data) {
return data.reduceRight((acc, cur) => {
return {
name: cur,
children:[acc]
};
}, { name: data.pop() });
}
let dataChapter = 'a/bb/ccc'.split('/');
let root = makeTree(dataChapter);
console.log(JSON.stringify(root, null, 2));
// {
// "name": "a",
// "children": [
// {
// "name": "bb",
// "children": [
// {
// "name": "ccc"
// }
// ]
// }
// ]
// }
var tree_pointer = 'root'; - tree_pointer is a string.
After that, you are trying to make hasOwnProperty from a line. Obviously, any console will tell you that there is no such method.
What you're trying to achieve with string concatenation is a mystery.
var chapters = dataChapter.split('\\');
var root = {}
var tree_pointer = {}; // зачем тут была строка?
for(var j=0, jlen = chapters.length; j < jlen; j++){
if(!tree_pointer.hasOwnProperty("name")) {
tree_pointer['name'] = chapters[j];
}
tree_pointer['children'] = {}; // зачем тут была строка?
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question