【问题标题】:Why .push() replacing the last object of JSON array?为什么 .push() 替换 JSON 数组的最后一个对象?
【发布时间】:2018-10-06 18:41:32
【问题描述】:

我开发了一个 Angular4 基本 CRUD 应用程序,它与渲染 JSON 数组数据的 nodejs 后端 API 交互。但是在使用 .push() 方法将对象添加到 JSON 数组时,它会将最后一个对象替换为要添加的新对象,而不是将其推送到数组中。

以下是Employee的定义:

export interface Employee {
id:number,
name:string,
review:string[],
peers:string[]
}

服务方法进行HTTP调用如下:

addEmployee(addedEmployee:Employee):Observable<Response>
{
return 
this._http.post("http://localhost:3001/add",addedEmployee)
.pipe(catchError(this.handleError));
}

将 Employee 对象添加到 JSON 对象数组的后端 API 代码如下:

app.post('/add',function(req,res){
var addedEmployee={};
addedEmployee.id=req.body.id;
addedEmployee.name=req.body.name;
addedEmployee.review=req.body.review;
addedEmployee.peers=req.body.peers;
employees.push(addedEmployee);
console.log('added');
res.json(employees);
})

后端JSON对象数组的前、中、后结构如下:

之前:

employees = [
{
    id: 1,
    name: "John Doe",
    review: ["Hardworking"],
    peers: ["admin", "Matt"]
},
{
    id: 2,
    name: "Matt Hofner",
    review: ["Hardworking"],
    peers: ["admin"]
},
{
    id: 3,
    name: "Judy Ruth",
    review: ["Focused"],
    peers: ["admin", "Matt"]
}
];

中级:

let addedEmployee:Employee = {
  id: 4,
  name: "Trudy",
    review:["Lazy"],
    peers: ["Matt"]
  };

决赛:

employees = [
{
    id: 1,
    name: "John Doe",
    review: ["Hardworking"],
    peers: ["admin", "Matt"]
},
{
    id: 2,
    name: "Matt Hofner",
    review: ["Hardworking"],
    peers: ["admin"]
},
{
    id: 4,
    name: "Trudy",
    review: ["Lazy"],
    peers: ["Matt"]
}
];

【问题讨论】:

  • 员工在哪里申报或提取?
  • 也许这会对你有所帮助:stackoverflow.com/questions/19054997/…
  • 刚刚尝试在浏览器控制台中进行推送,它可以正常工作。首先如何声明员工数组?作为 var employee = new Array[3] ?或代码 sn-p 中的内联初始化?
  • employees 数组已在另一个文件中声明,该文件已在后端脚本中导入。并且声明是内联的,就像在代码 sn-p 中一样。

标签: json node.js angular http express


【解决方案1】:

这很奇怪。这可能不是最好的解决方案,但请尝试 .concat() 方法:

app.post('/add',function(req,res){
var addedEmployee={};
var singleEmployeeArray = [];
addedEmployee.id=req.body.id;
addedEmployee.name=req.body.name;
addedEmployee.review=req.body.review;
addedEmployee.peers=req.body.peers;
singleEmployeeArray.push(addedEmployee);
employees.concat(singleNewEmployeeArray);
console.log('added');
res.json(employees);
})

【讨论】:

  • 抱歉,.concat() 也显示相同的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
  • 2019-07-29
  • 2013-01-31
  • 1970-01-01
相关资源
最近更新 更多