Felipe Carreón
Felipe Carreón

Reputation: 53

Best way to create new object from existing object with certain values

What is the best way to create new object from existing object with certain values, I mean i have one onbject and i want to create a new one with only the values that i need;

For example; Existing object

          data = [{
            "ID": "234324234",
            "calldate": "2018-03-25",
            "callend": "2018-03-25",
            "duration": "00:32",
            "connect_duration": "00:01",
            "progress_time": "2",
            "first_rtp_time": "2",
            "caller": "3243242342",
            "caller_domain": "XXX.XXXX.XXX",
          }, {
            "ID": "5675675",
            "calldate": "2018-03-12",
            "callend": "2018-03-12",
            "duration": "00:45",
            "connect_duration": "00:04",
            "progress_time": "2",
            "first_rtp_time": "2",
            "caller": "878678865",
            "caller_domain": "XXX.XXXX.XXX",
          }]

new Object required;

          new_object = [{
            "ID": "234324234",
            "calldate": "2018-03-25",
            "callend": "2018-03-25",
            "caller": "3243242342",
          }, {
            "ID": "5675675",
            "calldate": "2018-03-12",
            "callend": "2018-03-12",
            "caller": "878678865",
          }]

Upvotes: 0

Views: 90

Answers (2)

Davo
Davo

Reputation: 566

You can use class-transformer.

  1. Create a class with all the properties you need
  2. Convert plain (literal) objects to class (constructor) objects with proper options.

You can also look at the implementation of plainToClass and implement your own.

Upvotes: 1

Kidas
Kidas

Reputation: 329

you can do something like that by using map function

const new_object = data.map(({ ID, calldate, callend, caller }) => {
    return { ID, calldate, callend, caller };
});

Upvotes: 3

Related Questions