Angular 2 - 使用HTTP Post requset将数据添加到嵌套的json

时间:2016-08-20 19:05:13

标签: javascript json angular angular2-http

我有一个具有以下结构的JSON文件:

let data = [
      {
        item: '1',
        details:
          [
            {name: 'name1', address: 'address1'},
            {name: 'name2', address: 'address2'},
            {name: 'name3', address: 'address3'}
          ]
      },
      {
        item: '2',
        details:
          [
            {name: 'name1', address: 'address1'},
            {name: 'name2', address: 'address2'},
            {name: 'name3', address: 'address3'}
          ]
      }
    ];

我想添加嵌套的JSON对象(子)。 例如,要向“Item1”的详细信息添加另一个条目,如下所示:

      item: '1',
      details:
      [
          {Name: "name1", address: 'address1 "},
          {Name: "name2", address: "address2"},
          {Name: 'name3', address: 'address3'},
        **{Name: 'name4', address: 'address4'}**
      ]

如何使用HTTP Post请求执行此操作? (JSON文件是本地的,我使用“InMemoryBackendService”)

1 个答案:

答案 0 :(得分:0)

如果你正在使用Typescript写作:

public addDetail(itemId: string, detailToAdd: any): void {
    data.find(i => i.item === itemId).details.push(detailToAdd);
}

这在ES5中表示为

function addDetail(itemId, detailToAdd) {
    data.find(function (i) { return i.item === itemId; }).details.push(detailToAdd);
}