skip to Main Content

I have an array in my Angular class containing number and object as shown below.

What I want to do is recreate the array with only number like so [5,8,9,1,7] i.e. I get the id of the object inside the array and append it to the array.

allowedDepartmentAccess = [
    5,
    8,
    9,
    {
        "id": 1,
        "name": "Human Resource",
        "abbreviation": "HR"
    },
    {
        "id": 7,
        "name": "Warehouse",
        "abbreviation": "WH"
    }
]

2

Answers


  1. In Angular, you can achieve this by using the map operator to transform each element of the array. If an element is a number, keep it as is; if it’s an object, extract its "id" property. Here’s an example:

    const newArray = allowedDepartmentAccess.map(item =>
          typeof item === 'number' ? item : item.id
        );
    console.log(newArray);
    
    Login or Signup to reply.
  2. You can use Array.prototype.reduce() to achieve this.

    const allowedDepartmentAccess = [
      5,
      8,
      9,
      {
        "id": 1,
        "name": "Human Resource",
        "abbreviation": "HR"
      },
      {
        "id": 7,
        "name": "Warehouse",
        "abbreviation": "WH"
      }
    ];
    
    
    
    function getNumbersFromArray(arr) {
      return arr.reduce((result, item) => {
        if (typeof item === 'number') {
          result.push(item);
        } else if (typeof item === 'object' && item.id !== undefined && typeof item.id === 'number') {
          result.push(item.id);
        }
        return result;
      }, []);
    }
    
    
    const numbersArray = getNumbersFromArray(allowedDepartmentAccess);
    console.log(numbersArray);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search