M
M
Mike2017-05-03 18:17:24
JavaScript
Mike, 2017-05-03 18:17:24

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'
    }]
  }]
}

It turns out that I need to check at each iteration whether name exists at the current level, if it does not exist, then add it and create children for the next iteration. Here is a piece of code that the console swears at:
...
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';
}
...

Tell me how to solve this problem? I feel that most likely there is not enough eval () ...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
alex, 2017-05-03
@dillix

function makeTree(data) {
  return data.reduceRight((acc, cur) => {
    return {
      name: cur,
      children:[acc]
    };
  }, { name: data.pop() });
}

spoiler
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"
//         }
//       ]
//     }
//   ]
// }

N
Nicholas, 2017-05-03
@healqq

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.

E
Evgeny Tereshchenko, 2017-05-03
@Jman

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 question

Ask a Question

731 491 924 answers to any question