无法将对象添加到对象时

时间:2015-08-12 04:23:29

标签: javascript json

尝试向对象添加值。该对象从一开始就由数据库请求生成,该请求包含许多entires。样本条目(比如数字0)如下所示:

{ _id: 55c8a069cca746f65c98369d,
  fulltext: 'Finance',
  alias: 'Finance',
  level: 0,
  fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP',
  __v: 0,
  _parrent: [] 
}

现在我想为这个对象添加一个额外的数组。一个空的结构,其中将有许多其他列表。我首先使用.push,但该对象没有push函数。这个已完成几轮,所以最新版本如下:

我想要的结构是:

    { _id: 55c8a069cca746f65c98369d,
      fulltext: 'Finance',
      alias: 'Finance',
      level: 0,
      fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP',
      __v: 0,
      _parrent: [] 
      childs: [] 
}

此时我并没有把任何东西放到孩子身上(因为孩子似乎保留了孩子,虽然它可能会起作用,但是当代码已经破坏时,他们真的不想尝试改变它),基本上只是添加一个空槽来将类似的对象放入后续处理的一部分。 非常奇怪 更改代码如下:     console.log(" Root记录现在" + rootRecord);     rootRecord.childs = 1;     console.log(" Alias是" + rootRecord.alias);     console.log(" Child is" + rootRecord.childs);     console.log("完整的结构是:\ n" + rootRecord)

我得到以下输出

Alias is Finance
Child is 1
The complete structure is: 
{ _id: 55c8a069cca746f65c98369d,
  fulltext: 'Finance',
  alias: 'Finance',
  level: 0,
  fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP',
  __v: 0,
  _parrent: [] }

所以我可以阅读rootRecord.childs,但它没有列出,它几乎就像它是一个"隐藏"以某种方式变量。

违规代码

                console.log("Creating root structure");
                var roots = docs[doc];
                console.log("Root from docs: \n" + docs[doc])
                console.log("Sealed: " + Object.isSealed(docs[doc]));
                console.log("Frozen " + + Object.isFrozen(docs[doc]));
                console.log("Is Extendable: " + isExtendable(docs[doc]));
                console.log("Is Extensible(es6): " + Object.isExtensible(docs[doc]));
                for (var root in docs[doc]){
                    var rootRecord = docs[doc][root];
                    console.log ("Root record now " + rootRecord);
                    rootRecord.childs = [];
                    console.log("Now its " + rootRecord);
                    returnStructure.push(rootRecord);
                    console.log("returnStructure is now:\n" + returnStructure);
                    console.log("And first id is " + returnStructure[0]['_id'])

                }

提供以下输出:

Creating root structure
Root from docs: 
{ _id: 55c8a069cca746f65c98369d,
  fulltext: 'Finance',
  alias: 'Finance',
  level: 0,
  fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP',
  __v: 0,
  _parrent: [] }
Sealed: false
Frozen 0
Is Extendable: true
Is Extensible(es6): true
Root record now { _id: 55c8a069cca746f65c98369d,
  fulltext: 'Finance',
  alias: 'Finance',
  level: 0,
  fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP',
  __v: 0,
  _parrent: [] }
Now its { _id: 55c8a069cca746f65c98369d,
  fulltext: 'Finance',
  alias: 'Finance',
  level: 0,
  fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP',
  __v: 0,
  _parrent: [] }
returnStructure is now:
{ _id: 55c8a069cca746f65c98369d,
  fulltext: 'Finance',
  alias: 'Finance',
  level: 0,
  fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP',
  __v: 0,
  _parrent: [] }
And first id is 55c8a069cca746f65c98369d

完整源代码

var mongoose = require("mongoose");
var morgan = require('morgan');             // log requests to the console (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var async = require('async');
mongoose.connect('mongodb://localhost/ResourceProfiles');
//var ObjectId = require('mongoose').ObjectID;
var isExtendable = require('is-extendable');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;


var Profile = mongoose.model('Profile', {
    alias: String,
    img: String,
    name: String,
    summary: String,
    CV: String,
    keys: String,
    avail: String,
    agent: String,
    __v: {type: Number, select: false},
    comp: { type: Number, default: 0 },
    comn: { type: Number, default: 0 },
    intp: { type: Number, default: 0 },
    intn: { type: Number, default: 0 },
    orgp: { type: Number, default: 0 },
    orgn: { type: Number, default: 0 },
    swep: { type: Number, default: 0 },
    swen: { type: Number, default: 0 },
    pssp: { type: Number, default: 0 },
    pssn: { type: Number, default: 0 },
    pep: { type: Number, default: 0 },
    pen: { type: Number, default: 0 },
    gtemp: { type: Number, default: 0 },
    gtemn: { type: Number, default: 0 }
});

var Skill = mongoose.model('Skill', {
    alias: String,
    fulltext: {
        type: String
        , required: true
        , unique: true
    },
    fullurl: String,
    level: Number,
    _parrent: [{ type: ObjectId, ref: 'Skill'}],

})


    console.log("Lets see if we can't figure out this one once and for all");
    var queries= [];
    var maxLevels = 1;
    [0,1,2,3,4].forEach(function(i){
        console.log("Looking for "+ i)
        queries.push(function (cb) {
            console.log("Seaching for "+ i)
            Skill.find({level: i}).exec(function (err, docs) {
                if (err) {
                    throw cb(err);
                }

                // do some stuff with docs & pass or directly pass it
                cb(null, docs);
            });
        });
    })
    console.log("All requests generated");
    async.parallel(queries, function(err, docs) {
        // if any query fails
        if (err) {
            throw err;
        }
        var returnStructure = [];
        console.log("This is what we got back")
        for (var doc in docs){
                if ( docs[doc].length === 0 ){
                    console.log("No entries in level " + doc)
                } else {
                    console.log("Processing " + docs[doc].length + " for level " + doc)
                    if ( doc === "0" ) {
                        console.log("Creating root structure");
                        var roots = docs[doc];
                        console.log("Root from docs: \n" + docs[doc])
                        console.log("Sealed: " + Object.isSealed(docs[doc]));
                        console.log("Frozen " + + Object.isFrozen(docs[doc]));
                        console.log("Is Extendable: " + isExtendable(docs[doc]));
                        console.log("Is Extensible(es6): " + Object.isExtensible(docs[doc]));
                        for (var root in docs[doc]){
                            var rootRecord = docs[doc][root];
                            console.log ("Root record now " + rootRecord);
                            rootRecord.childs = [];
                            console.log("Now its " + rootRecord);
                            returnStructure.push(rootRecord);
                            console.log("returnStructure is now:\n" + returnStructure);
                            console.log("And first id is " + returnStructure[0]['_id'])

                        }
                    /*} else if ( doc === "1"){
                        var skills = docs[doc];
                        for (var skill in skills){
                            console.log("Need to find " + skills[skill].alias + " parrent " + skills[skill]._parrent);
                            for (var root in returnStructure) {
                                if ( returnStructure[root]["_id"].toString() === skills[skill]["_parrent"].toString()){
                                    console.log("Found parrent " + returnStructure[root].alias);
                                    var newSkill = [];
                                    var childs =  { childs: {}};
                                    newSkill.push(skills[skill]);
                                    newSkill.push(childs);
                                    console.log("This is it " + returnStructure);
                                    returnStructure[root].childs.push(newSkill);
                                }
                            }
                            console.log(returnStructure);
                        }
                    } else if ( doc === "2"){
                        var skills = docs[doc];
                        for (var skill in skills){
                            console.log("Need to find " + skills[skill].alias + " parrent " + skills[skill]._parrent);
                            for (var root in returnStructure){
                                //var parrents= returnStructure[root].childs;
                                for (var parrent in returnStructure[root].childs){
                                    console.log("Lets compare \n" + returnStructure[root].childs[parrent]._id + "\n" + skills[skill]._parrent);
                                    if(  returnStructure[root].childs[parrent]._id.toString() === skills[skill]["_parrent"].toString() ){
                                        console.log("Hello found " + returnStructure[root].childs[parrent].childs);
                                        skills[skill].childs = [];
                                        console.log(skills[skill])
                                        returnStructure[root].childs[parrent].childs.push(skills[skill])

                                    }
                                }
                            }
                        }
                        */
                    }

            //    }

            }


        }

    })

3 个答案:

答案 0 :(得分:0)

当您使用对象而不是数组时,您应该只分配此值:

var obj = {
   a: 1,
   b: "str"
};
obj.c = 3; // not obj.push(3); or whatever else

你的例子很不清楚。据我了解,您希望在rootsreturnStructure中分配一个对象数组。否则,您只需在对象中重写值。

如果你这样做:

returnStructure.childs = roots; // not children, childS, really? :)

然后,您的对象将如下所示:

{ 
    _id: '55c8a069cca746f65c98369d',
    fulltext: 'Finance',
    alias: 'Finance',
    level: 0,
    fullurl: 'http://127.0.0.1/wiki/index.php/FMP',
    __v: 0,
    _parrent: [],
    childs: [
        {"all": "objects"},
        {"from": "roots"},
        {"whatever": "they are"}
    ]
}

如果我错了,请澄清并添加一些代码 - 你的roots对象是什么;什么是returnStructure以及在分配后应该如何。

<强>更新
在任何其他情况下,这就是如何创建一个空数组作为对象的一部分:

returnStructure.childs = [];

然后,您可以像这样添加任何对象:

returnStructure.childs.push(obj);
returnStructure.childs.push(1);

答案 1 :(得分:0)

如果这是您当前的数据结构:

var data = { _id: 55c8a069cca746f65c98369d,
  fulltext: 'Finance',
  alias: 'Finance',
  level: 0,
  fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP',
  __v: 0,
  _parrent: [] 
}

并且,您只想使用空数组向其添加childs属性,然后您可以将该新属性分配给该对象。

data.childs = [];

这会给你这个结果:

{ _id: 55c8a069cca746f65c98369d,
  fulltext: 'Finance',
  alias: 'Finance',
  level: 0,
  fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP',
  __v: 0,
  _parrent: [], 
  childs: []
}

如果您想在childs数组中添加一些项目,可以执行以下操作:

data.childs.push("hello");
data.childs.push("goodbye");

或者,如果你想将一个对象推入数组而不是上面的字符串,你可以这样做:

data.childs.push({greeting: "hellow"});

对象属性只是直接分配为data.childs = []。如果该属性不存在,则将创建该属性并给出该初始值。如果该属性已存在,则其值将更改。

.push()用于将项添加到已存在的数组的末尾,因此您无法在对象或尚未包含数组的属性上使用.push()

答案 2 :(得分:0)

所以经过多次讨论之后,我设法弄明白我哪里出错了,而且它是在数据对象而不是代码中。 因此docs[doc]中的数据是对象,或对象中的一组对象,或其他有趣的东西。

  • 它有时会作为一个对象作出反应(例如,如果你要求提供docs [doc] .alias)。
  • 如果您刚刚询问其中的内容(如在console.log(docs [doc]中),它返回的内容看起来像一个JSON对象(此时应该已经意识到某些东西已经启动,它应该有返回[Object Object])
  • 如果您尝试更改或添加任何内容,那就是问题开始时的问题。

在这种情况下,我运行了一个自己的对象列表(for (var id in docs[doc]){console.log("ID: "+id+" data:\n " + docs[doc][id])}这返回了很多东西,包括一个名为toJSON()的函数。猜猜是什么,将行改为var rootRecord = docs[doc][id].toJSON();排序问题。

很抱歉,如果我错过了一些非常明显的东西,但很确定这不是正常行为。认为可能是异步或猫鼬增加了奇怪的结构。