首页 > 解决方案 > Typescript - Check values in one array are present in another

问题描述

I have the following array. I am using this array to dynamically produce checkboxes on my UI. This is being used to save user config as to what they will be able to see in a nav menu.

  accessLevels: any = [
    {
      description: "Properties",
      type: '1',
      selected: false
    },
    {
      description: "Equipment",
      type: '2',
      selected: false
    },
    {
      description: "Jobs",
      type: '3',
      selected: false
    },
    {
      description: "Calender",
      type: '4',
      selected: false
    }
]

I am making a call to an API which returns me an array of the users config. So what I will get is an array of the pages and their type like this:

    {
      description: "Equipment",
      type: '2'
    },
    {
      description: "Jobs",
      type: '3'
    }

In the array returned from the API I am just getting the values that should appear checked on the check boxes so what I want to do is loop through the returned array and check if any of the types match any types in the checkbox array if they do I want to set 'selected' to true. Thus checking the checkbox.

Here is what I have so far:


  async loadLandlordConfig(key: string) {

    const result = await this.userService.loadLandlordConfig(key);

    //let accessLevels = [];

    this.selectedApiValues = result[0].accessLevels;

    this.selectedApiValues.forEach((selectedValue)=> {

    });
  }

Im not sure how to cross check the values and then change selected to true.

Hope I have made everything clear enough. Any questions please ask. All help appreciated.

标签: arraysangulartypescriptcheckbox

解决方案


You can achieve what you want with the following simple example :

let accessLevels = [
    {
      description: "Properties",
      type: '1',
      selected: false
    },
    {
      description: "Equipment",
      type: '2',
      selected: false
    },
    {
      description: "Jobs",
      type: '3',
      selected: false
    },
    {
      description: "Calender",
      value: '4',
      selected: false
    }
]

let api = [
    {
      description: "Equipment",
      type: '2'
    },
    {
      description: "Jobs",
      value: '3'
    }
];

for(var i = 0; i < accessLevels.length; i++) {
     accessLevels[i].selected = api.find(e => e.description === accessLevels[i].description) ? true : false;
}

console.log(accessLevels);


推荐阅读