比较对象数组并删除特定项目

时间:2019-08-28 21:13:56

标签: javascript arrays comparison

arr1 = [
    {
        name: "will",
        value: "1"
    },
    {
        name: "nelson",
        value: "3"
    }
];

arr2 = [
    {
        name: "will",
        value: 1,
        submenu: [
            {
                name: "ralph",
                value: 2    
            }
        ]
        }
]

然后从第二个数组中删除拉尔夫。我已经创建了一个函数来执行此操作,但是只检查第一个元素而不验证子菜单。

comparador(arrSecundario) {
    return (arrAtual) => {
      return arrSecundario.filter(function (other) {
        return other.value === arrAtual.value;
      }).length !== 0;
    };
  }

this.arr2.filter(this.comparador(this.arr1));

1 个答案:

答案 0 :(得分:0)

过滤后需要映射数组。您可以这样做,也可以添加“ prop ==='submenu'”,仅用于专门检查子菜单内部数组。

var arr1 = [
  {
    name: "will",
    value: "1"
  },
  {
    name: "nelson",
    value: "3"
  }
];

var arr2 = [
  {
    name: "will",
    value: 1,
    submenu: [
        {
          name: "ralph",
          value: 2    
        },
        // {
        //   name: "nelson",
        //   value: 3
        // }
    ]
  }
];

function filterComparador(arrSecundario) {
  return (arrAtual) => {
    return arrSecundario.filter((other) => {
      return other.value == arrAtual.value;
    }).length != 0;
  };
}

function mapComparador(arrSecundario) {
  return (arrAtual) => {
    Object.keys(arrAtual).forEach((prop) => {
       if (Array.isArray(arrAtual[prop])) {
          let propValue =  arrAtual[prop].filter(this.filterComparador(arrSecundario));
          if (propValue.length > 0) {
            arrAtual[prop] = propValue.map(this.mapComparador(this.arrSecundario));
          } else {
            delete arrAtual[prop]; 
          }           
       }
    });
    return arrAtual;
  };
}

var manipulatedArray = this.arr2.filter(this.filterComparador(this.arr1))
    .map(this.mapComparador(this.arr1));

console.log(manipulatedArray);