首页 > 解决方案 > 打破嵌套的一些或映射 JavaScript

问题描述

PC = {a:{ID: "abc",options:{x1:"100", x2:"200"}},b:{ID: "d",options:{x2:"100", x3:"200"}}}


pro = {
  "pro": [
    {
      "pID": "abc",
      "attributes": {
        "xyz": [
          "1",
          "2",
          "3"
        ],
        "foo": "フルプレミアム"
      }
    }
  ]
}
functionX() {
        let isND = true;
        if (pro === null || pro === [] || pro.length === 0) {
            return isND;
        } else if (pro.length > 0) {
             some(PC, (p) => {
                 some(p.options, (o, k) => {
                     some(pro, (item) => {
                        if (p.ID === item.pID && k === 'xyz') {
                        if (item.attributes[k] !== []) {
                            isND = false;
                        }
                    } else if (p.ID === item.pID && k !== 'xyz') {
                        if (item.attributes[k] !== '') {
                            isND = false;
                        }
                    }
                    });
                });
            });
        }
        return isND;
    }

我必须遍历 3 个不同的集合来检查我的状况并返回一个值。如果我的 if-else 条件之一满足,我正在尝试退出嵌套的 some or map。我尝试在 isND = false 之后传递 return true 但不起作用。有人可以帮助解决这个问题。

标签: javascriptlodash

解决方案


Array.prototype.some()如果任何回调返回,将提前退出,true这样你就可以return得到结果。

这不是很清楚,但似乎您想在返回逆向时使用此“提前退出”功能。像这样的东西怎么样...

// ignoring "if (pro === null || pro === [] || pro.length === 0)" for this example

// return the inverse
return !Object.values(PC).some(({ ID, options }) => {
  return Object.entries(options).some(([k, o]) => {
    // here "k" is one of your "x1", "x2", etc keys
    // and "o" is the corresponding value

    return pro.pro.some(item => {
      // return "true" if any of your "conditions" are met
    })
  })
})

推荐阅读