忽略json的最后一个元素 [英] Ignore the last element of a json

查看:180
本文介绍了忽略json的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Json结果来自API,如下

My Json result from the API is as below

Json结果:

"Issues": [{
    "Id": null,
    "Key": null,
    "Values": [{
        "Key": "Display Name",
        "Value": "Rya"
      },
      {
        "Key": "UserName",
        "Value": "RH"
      },
      {
        "Key": "Count",
        "Value": "350"
      }
    ]
  },
  {
    "Id": null,
    "Key": null,
    "Values": [{
        "Key": "Display Name",
        "Value": "Mike"
      },
      {
        "Key": "UserName",
        "Value": "ML"
      },
      {
        "Key": "Count",
        "Value": "90"
      }
    ]
  }
]

我做了一个映射,做如下 -

I did a mapping by doing as below-

.Issues.map(o =>
  o.Values.reduce((acc, {
      Key,
      Value
    }) =>
    (acc[Key] = Value, acc), {}));

映射的结果如下 -

The result of the mapping is as below-

{ "Display Name": 'Rya', "UserName" : "RH", value: 350 },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90 }

所需结果:

{ "Display Name": 'Rya', "UserName" : "RH" },
{ "Display Name": 'Mike', "UserName" : "ML"}

根据我的要求,我想忽略显示的最后一个元素在期望的结果。

In my requirement, I want to ignore the last element as shown in the desired result.

推荐答案

一个解决方案是在reduce之前添加一个过滤器,以过滤出不需要的 Count property。

One solution is to add a filter before the reduce to filter out objects with the unwanted Count property.

.Issues.map(o =>
  o.Values
    .filter(({ Key }) => Key !== 'Count')
    .reduce((acc, {
      Key,
      Value
    }) =>
    (acc[Key] = Value, acc), {}));

您还可以在减少期间通过不添加对象在键==='Count'

You could also do this filtering inline during the reduction by not adding objects when Key === 'Count'.

注意:JS对象中没有最后一个属性。它是一个属性的集合,其实际顺序依赖于实现并且不可靠。例如,在不同的浏览器和平台上打印您的对象可以给出任何顺序,没有任何保证一致性。

Note: There is no such thing as the last property in a JS object. It is a collection of properties whose actual order is implementation dependent and unreliable. For example, printing your object in different browsers and platforms could give any order whatsoever, nothing guarantees that consistency.

这篇关于忽略json的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆