节点js:util.inspect添加对象到数组

节点js:util.inspect添加对象到数组

问题描述:

我有一个问题,我无法弄清解决方案很长一段时间。节点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); 

如何访问的属性和它的价值?

,我有一般的想法是创建人,将它们存储在一个数组与他们进一步工作(更新,删除),更改姓氏等

能否请你告诉我,这将是最好的解决办法为了那个原因。

util.inspect(fields)返回fields对象的字符串表示形式(主要用于调试目的)。

从我可以告诉,你要的对象fields本身在阵列上:

arr.fix.push(fields); 

如果你想登录该数组,你不应该使用+,因为这将投该阵列为一个字符串,但阵列通过作为单独的参数:

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

或日志它作为JSON:

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