微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

基于非常深的嵌套集合中的键值返回对象的有效解决方案?

如何解决基于非常深的嵌套集合中的键值返回对象的有效解决方案?

我有一个包含许多对象的集合。所有的对象都是深度嵌套的。我想根据键值返回对象。但关键是在嵌套对象的最后。让我粘贴一个数据示例:

[
{
  "_id": "5cac8858f0c65f0010451f6c","dealsAllowed": [
    {
      "plan": "plan1","newPlanDeal": {
        "discount": 10,"discountType": "points",},"oldplanDeal": {
        "discount": 40,}
    },{
      "plan": "plan12","oldplanDeal": {
        "discount": 50,"discountType": "price",{
      "plan": "page45","newPlanDeal": {
        "discount": 20,{
      "plan": "wall5","newPlanDeal": {
        "discount": 30,{
      "plan": "mars4","oldplanDeal": {
        "discount": 60,{
      "plan": "glob07",{
      "plan": "advent11",{
      "plan": "advent1","oldplanDeal": {
        "discount": 70,}
    }
  ]
},{
    "_id": "5ca73621a926e60010e7dbe4","dealsAllowed": [
        {
            "plan": "rover10","newPlanDeal": {
                "discount": 75,"oldplanDeal": {
                "discount": 75,}
        }
    ]
},.....
]

现在为了找到所需的对象,我检查属性discountType”的值是“points”还是“price”。我得到的任何一个。我的解决方案如下:

let result = []
 _.forEach(allDealObjects,deal =>
     _.forEach(deal['dealsAllowed'],plan => {
         _.forEach(plan,type => {
             type.discountType === 'price' ? result.push(deal) : null
         })
      })
 )

现在我的特定解决方案工作正常。而且它也更容易阅读。我只是想知道是否有更好的解决方案或紧凑的解决方案,因为在未来会再次出现深度嵌套的对象,并且它们必须是比循环它们更好的方法。我对吗?是否有更好的做法可供我采用。

解决方法

使用 .filter.map(而不是 _.forEach.push 会更惯用,也会减少嵌套。

let allDealObjects = [{
    "_id": "5cac8858f0c65f0010451f6c","dealsAllowed": [{
        "plan": "plan1","newPlanDeal": {
          "discount": 10,"discountType": "points",},"oldPlanDeal": {
          "discount": 40,}
      },{
        "plan": "plan12","oldPlanDeal": {
          "discount": 50,"discountType": "price",{
        "plan": "page45","newPlanDeal": {
          "discount": 20,{
        "plan": "wall5","newPlanDeal": {
          "discount": 30,{
        "plan": "mars4","oldPlanDeal": {
          "discount": 60,{
        "plan": "glob07",{
        "plan": "advent11",{
        "plan": "advent1","oldPlanDeal": {
          "discount": 70,}
      }
    ]
  },{
    "_id": "5ca73621a926e60010e7dbe4","dealsAllowed": [{
      "plan": "rover10","newPlanDeal": {
        "discount": 75,"oldPlanDeal": {
        "discount": 75,}
    }]
  },];

let result = allDealObjects
  .filter(deal => deal.dealsAllowed
    .flatMap(planObj => Object.values(planObj))
    .some(plan => plan.discountType === 'price'));

console.log(result)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。