JS通过另一种对象过滤对象数组

时间:2019-02-24 18:20:10

标签: javascript arrays object ecmascript-6 filter

我有三个对象数组:

extension ViewController: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return string.rangeOfCharacter(from: .whitespacesAndNewlines) == nil
    }

}

我需要没有以下内容的新名称数组:

  • 已选择所有可能的参数
  • 如果给定名称没有参数,则只能选择一次

在这种情况下,我的预期输出应该是

const names = [
  { value: "Time" },
  { value: "Angle" },
  { value: "Speed" },
  { value: "Mass" }
];

const params = [
  { name: "Time", value: "s" },
  { name: "Time", value: "h" },
  { name: "Time", value: "m" },
  { name: "Angle", value: "rad" },
  { name: "Angle", value: "grade" }
];

const selected = [
  { id: 1, name: "Time", param: "s" },
  { id: 2, name: "Time", param: "h" },
  { id: 3, name: "Time", param: "m" },
  { id: 4, name: "Angle", param: "grade" },
  { id: 5, name: "Speed", param: null }
];

1 个答案:

答案 0 :(得分:1)

您可以按

进行过滤
  • 对参数null
  • 没有任何价值
  • 过滤后的参数和所选项目的长度不相等,并且长度也没有。

const
    names = [{ value: "Time" }, { value: "Angle" }, { value: "Speed" }, { value: "Mass" }],
    params = [{ name: "Time", value: "s" }, { name: "Time", value: "h" }, { name: "Time", value: "m" }, { name: "Angle", value: "rad" }, { name: "Angle", value: "grade" }],
    selected = [ { id: 1, name: "Time", param: "s" }, { id: 2, name: "Time", param: "h" }, { id: 3, name: "Time", param: "m" }, { id: 4, name: "Angle", param: "grade" }, { id: 5, name: "Speed", param: null }],
    result = names.filter(({ value }) => {
        const check = ({ name }) => name === value,
              pl = params.filter(check).length,
              sl = selected.filter(check).length;
  
        return !selected.some(o => o.name === value && o.param === null)
            && !(pl === sl && pl);
    });

console.log(result);