如何从一个嵌套数组中删除数据,如果它与另一个数组 ID 匹配

问题描述 投票:0回答:4

如果嵌套数组与主数组的 id 匹配,我需要删除它。

arrayOne =

[
    {
        "id": "1",
        "role": [
            "pos_cashier_1",
            "pos_manager"
        ]
    },
    {
        "id": "2",
        "role": [
            "pos_manager",
            "pos_cashier_2"
        ]
    }
]

arrayTwo

[
    {
        "label": "Sessions Sandringham",
        "value": "1"
    },
    {
        "label": "Sessions West Brunswick",
        "value": "2"
    },
    {
        "label": "Global",
        "value": null
    }
]

如果 arrayOne 中的值 == id,我需要删除 arrayTwo 中的数组。 有人可以帮帮我吗...

javascript reactjs arrays multidimensional-array arraylist
4个回答
0
投票

您可以先创建第一个数组中所有 id 的

Set
,然后根据该
Set
中是否存在 value 属性过滤第二个数组。

let arr1=[{id:"1",role:["pos_cashier_1","pos_manager"]},{id:"2",role:["pos_manager","pos_cashier_2"]}],arr2=[{label:"Sessions Sandringham",value:"1"},{label:"Sessions West Brunswick",value:"2"},{label:"Global",value:null}];
let ids = new Set(arr1.map(o => o.id));
let res = arr2.filter(x => !ids.has(x.value));
console.log(res);


0
投票

首先创建一组 id 更有效,但您也可以像这样使用

find
将其作为一个单行来完成:

const arr1 = [{"id":"1","role":["pos_cashier_1","pos_manager"]},{"id":"2","role":["pos_manager","pos_cashier_2"]}]
const arr2 = [{"label":"Sessions Sandringham","value":"1"},{"label":"Sessions West Brunswick","value":"2"},{"label":"Global","value":null}]

console.log(arr2.filter(({value:v})=>!arr1.some(({id})=>id===v)))


0
投票

您也可以使用

find
filter

const arr1 = [{"id":"1","role":["pos_cashier_1","pos_manager"]},{"id":"2","role":["pos_manager","pos_cashier_2"]}]
const arr2 = [{"label":"Sessions Sandringham","value":"1"},{"label":"Sessions West Brunswick","value":"2"},{"label":"Global","value":null}]

let output = arr2.filter(d => d.value == arr1.find(info => info.id == d.value))

console.log(output)

0
投票

您可以像这样使用

filter
some

const arrayOne = [
  {
    "id": "1",
    "role": [
      "pos_cashier_1",
      "pos_manager"
    ]
  },
  {
    "id": "2",
    "role": [
      "pos_manager",
      "pos_cashier_2"
    ]
  }
];

const arrayTwo = [
  {
    "label": "Sessions Sandringham",
    "value": "1"
  },
  {
    "label": "Sessions West Brunswick",
    "value": "2"
  },
  {
    "label": "Global",
    "value": null
  }
];
const filtered = arrayTwo.filter(({ value }) => !arrayOne.some(({ id }) => id === value));
console.log(filtered)

© www.soinside.com 2019 - 2024. All rights reserved.