错误:在节点Js中创建嵌套Json对象时,无法读取未定义的属性“名称”

时间:2018-07-20 11:01:54

标签: json node.js nested

myObj = {
    "name":"John",
    "age":30,
    "vehicles": {
        "cars":["Ford", "BMW", "Fiat"],
        "bikes":["Suziki", "BMW", "Yamaha"],
        "other":["Honda", "Scoda", "Bajaj"]
    }
 }

如何创建这种嵌套对象?

var myObj = [];
"SELECT * FROM categories"; // done query and saved result into var res
for(var i=0; i<res.length; i++){
    myObj[i] = {};
    myObj[i].id = res[i].id;
    myObj[i].title = res[i].title;
    myObj[i].posts = {};

    "SELECT * FROM posts WHERE id = "+res[i].id+" AND user = John"; // done query and saved result into var nres
    for(var x=0; x<nres.length; x++){
        myObj[i].posts.john[x] = nres[x];
    } //sub for loop within main loop
    "SELECT * FROM posts WHERE id = "+res[i].id+" AND user = Johny"; // done query and saved result into var nnres
    for(var y=0; y<nnres.length; y++){
        myObj[i].posts.johny[y] = nnres[y];
    } //sub for loop within main loop
    "SELECT * FROM posts WHERE id = "+res[i].id+" AND user = Johns"; // done query and saved result into var nnnres
    for(var z=0; z<nnnres.length; z++){
        myObj[i].posts.johns[z] = nnnres[z];
    } //sub for loop within main loop

} //main for loop end

我在php中创建了它。但在NodeJs中显示错误,

  

无法读取未定义的属性“帖子”

这就是我所需要的

[  {“ id”:“ catagoryId”,“ title”:“ categoryTitle”,“ posts”:{[postTitle,postContent,postTags],[],...,[]}},  {},  ...,  {} ]

结论: php更容易编写代码,php本身管理变量。 但是在JavaScript中,需要以正确的方式声明变量,这很困难。

1 个答案:

答案 0 :(得分:1)

似乎您认为您正在从数据库中查询,但您未调用MySQL

var res = "SELECT * FROM categories";
for(var i=0; i<res.length; i++){
    myObj[i] = {};
    myObj[i].id = res[i].id;
    myObj[i].title = res[i].title;
    myObj[i].posts = {};

res(及以后的nres)变量包含字符串,实际上是您放入其中的SQL命令。因此res[i]是一个字符,因此没有idposts等键。


错误显示“无法读取未定义的属性'posts'”。在上面的代码中,posts属性是在myObj[i]上访问的,如下所示:myObj[i].posts

根据错误,myObj[i]undefined。但是您的代码定义了myObj[i]myObj[i] = {}),因此问题可能出在您未发布的代码中。