Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

How to remove some values from object in Angular?

Get support on Angular & Typescript related technology.
Post Reply
admin
Site Admin
Posts: 45

How to remove some values from object in Angular?

Post by admin » Fri Aug 23, 2019 2:25 pm

Let's assume I have some object like this

Code: Select all

const values = {
    test: {
        level: 'TEST'
    },
    overview: {
        active: true
    },
    product: {
        active: true,
        allowed: false
    },
    report: {
        todo: true,
        show: true,
        use: true
    }
};
And I want to remove properties report and product from this object,then:

app.component.ts

Code: Select all

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular';
  newObj:any;
  prop:any;
  constructor(){}
  ngOnInit(){

    const values = {
    test: {
        level: 'TEST'
    },
    overview: {
        active: true
    },
    product: {
        active: true,
        allowed: false
    },
    report: {
        todo: true,
        show: true,
        use: true
    }
};

 this.prop = ['report', 'product'] // list of props you want to omit

 this.newObj = Object.keys(values).reduce((object, key) => {
  if (!this.prop.includes(key)) {
    object[key] = values[key]
  }
  return object;
}, {})

console.log(this.newObj);

  }

  
}

Demo - https://stackblitz.com/edit/angular-fpfrbf open console window below to preview window

Post Reply