Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove properties from an object array? [duplicate]

I am trying to remove a property from an object array.

export class class1 {
  prop1: string;
  prop2: string;
  prop3: string;
}
export class class2 {
  myprop = [
    { prop1:'A', prop2:"1", prop3:"descr1" },
    { prop1:'B', prop2:"2", prop3:"descr2" },
    { prop1:'C', prop2:"3", prop3:"descr3" },
  ];
  get(): class1[] {
    return this.myprop ;
  }
  add(value: class1): void {
    this.myprop.push(value);
  }
}
var var1 = class2.get();
var var2 = 

I would like var2 contain something like this.

  [
    { prop1:'A', prop3:"descr1" },
    { prop1:'B', prop3:"descr2" },
    { prop1:'C', prop3:"descr3" },
  ];

Is there a way to convert/cast var1 into the above? In other words, I would like to remove prop2 from var1 object array and assign it to var2. How can I do that?

like image 794
Shawn Avatar asked May 14 '16 05:05

Shawn


2 Answers

You can delete object property like this e.g.

    var myprop = [
        {prop1: 'A', prop2: "1", prop3: "descr1"},
        {prop1: 'B', prop2: "2", prop3: "descr2"},
        {prop1: 'C', prop2: "3", prop3: "descr3"},
    ];

    myprop = myprop.filter(function (props) {
        delete props.prop2;
        return true;
    });
    console.log(myprop);
like image 133
Ikhtiyor Avatar answered Sep 21 '22 06:09

Ikhtiyor


This seems like a great time to use .map()

var var1 = class2.get();
var var2 = var1.map(obj => ({prop1: obj.prop1, prop3: obj.prop3}));

Short, sweet, and does what you want.

MDN docs for .map()

like image 36
Paarth Avatar answered Sep 22 '22 06:09

Paarth