【问题标题】:Trying to dynamically organize JSON object elements into different arrays based on values尝试根据值将 JSON 对象元素动态组织到不同的数组中
【发布时间】:2018-07-03 01:01:24
【问题描述】:

这是我正在使用的 JSON:

https://data.cityofnewyork.us/resource/xx67-kt59.json?$where=camis%20=%2230112340%22

我会使用不同的数据动态地进行查询,所以它可能会改变。

我实际上要做的是根据inspection_date 以某种方式将此数组中的元素组织成不同的数组。

因此,对于每个唯一的inspection_date 值,这些各自的检查将被放入其自己的集合中。

  1. 如果我事先知道日期,我可以轻松地遍历每个元素,然后将其推入一个数组。
  2. 有没有办法动态创建数组?

我的最终目标是能够在网页上使用 Angular 5 显示每组检查(基于检查日期)。我已经启动并运行了网站,并且所有的请求都在进行中。

所以,我试图最终达到这样的目标。但当然,在请求的响应中使用任何日期。

2016-10-03T00:00:00

列出检查

2016-04-30T00:00:00

列出检查

2016-04-12T00:00:00

列出检查

仅供参考,这是我正在使用的代码:

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.title = +params['camis']; // (+) converts string 'id' to a number
      this.q.getInpectionsPerCamis(this.title).subscribe((res) => {
        this.inspectionList = res;
          console.log(res);
      });
      // In a real app: dispatch action to load the details here.

    });

  }

我希望我能给你更多信息,但在这一点上,我只是想开始。

【问题讨论】:

  • array.reduce 似乎是一个很好的例子。您将向它传递一个函数,该函数将检查给定的inspection_date 是否作为键存在于当前对象中——如果不存在,则向该键添加一个空数组——然后只需使用array.push

标签: javascript arrays json sorting typescript


【解决方案1】:

我用 jQuery 写这个只是因为它对我来说更快,但它应该可以很好地转换为 Angular(我现在只是不想摆弄 Angular 应用程序)

如果您有任何问题,请告诉我。

$(function() {
  let byDateObj = {};
  $.ajax({
    url: 'https://data.cityofnewyork.us/resource/xx67-kt59.json?$where=camis%20=%2230112340%22'
  }).then(function(data) {
    //probably do a check to make sure the data is an array, im gonna skip that
    byDateObj = data.reduce(function(cum, cur) {
      if (!cum.hasOwnProperty(cur.inspection_date)) cum[cur.inspection_date] = [];
      //if the cumulative array doesn't have the inspection property already, add it as an empty array
      cum[cur.inspection_date].push(cur);
      //push to inspection_date array.
      return cum;
      //return cumulatie object
    }, byDateObj);
    //start with an empty object by default;
    console.log(byDateObj);
  }, console.error);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • 我必须做一些测试,但到目前为止,看起来它有效!我已经用 Java 做了一些 map/reduce,但还没有 JS。我必须检查一下并多练习一下!谢谢!
  • 很高兴为您提供帮助,如果您不确定如何修复的代码出现错误,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
相关资源
最近更新 更多