2016-11-20 98 views
0

我有一個問題,我無法弄清解決方案很長一段時間。節點js:util.inspect添加對象到數組

我正在使用NodeJS,我想存儲一個對象的數組,我通過發佈從其他網站接收數據。我用可怕的方式解析這個對象,並想用util.inspect來顯示它。此外,我想進一步與其屬性一起處理該對象。

我有我的數組:

const arr = { 
    fix: [] 
}; 


function CreatePerson (req, res) { 

    var form = new formidable.IncomingForm(); 
    form.parse(req, (err, fields, files) => { 
      var firstname = util.inspect(fields.firstname); 
      var lastname = util.inspect(fields.lastname); 
arr.fix.push(util.inspect(fields)); 

//Works fine - shows me the two properties of my person with the values 
console.log("Person" + util.inspect(fields)); 

// Works fine - shows me the given firstname 
console.log("Firstname: " + util.inspect(fields.firstname)); 

//This shows me the whole person with all properties as above 

console.log("Firstname " + arr.fix[0]); 

// If I want to show juste one property it does not work - I get undefined 

console.log("Firstname " + arr.fix[0].firstname); 

如何訪問的屬性和它的價值?

,我有一般的想法是創建人,將它們存儲在一個數組與他們進一步工作(更新,刪除),更改姓氏等

能否請你告訴我,這將是最好的解決辦法爲了那個原因。

回答

0

util.inspect(fields)返回fields對象的字符串表示形式(主要用於調試目的)。

從我可以告訴,你要的對象fields本身在陣列上:

arr.fix.push(fields); 

如果你想登錄該數組,你不應該使用+,因爲這將投該陣列爲一個字符串,但陣列通過作爲單獨的參數:

console.log("Firstname", arr.fix[0]) 

或日誌它作爲JSON:

console.log("Firstname %j", arr.fix[0])