How to get values from json object array and add to another array in angular

Viewed 3560

I have Following json object :

var arr =[{ 0:M: "LED" id: 1
mtype: "KIOSK PACKAGE"
part_fees: 200
tb_bid_upins: 1
tech_bid_flag: 0
tot_media: 0
type: "Road Stretch"
upin: "AMCADVT1415C0123"
upin_id: "2"
}, { 1:M: "LED"
id: 1
mtype: "KIOSK PACKAGE"
part_fees: 200
tb_bid_upins: 1
tech_bid_flag: 0
tot_media: 0
type: "Road Stretch"
upin: "AMCADVT1415C0123"
upin_id: "2" }]

Now it has two values,but it can have multiple value because it is fetch from database. From this json i wnat to pick values with key upin,mtype,land and add to another array.

I have tried following

for(let item of data){
    // this.console.log(item)
     this.upins = item.upin;
     this.console.log(this.upins);
    }
this.console.log(this.upins);```

It shows last index value

I want result as follows

var arr = [{
upins: abc,
mtyp:xyz,
land:123
},{
upins:123,
mtype:pqr,
land:555
}]
4 Answers

Assuming data as array you should insert data in a new empty array.

const arr = [];

// extract upin, mtype, land from the original array
for (let item of data) {
  arr.push({
    upin: item.upin,
    mtype: item.mtype,
    land: item.land
  });
}

// OR

const arr = data.map((item) => {
  return {
    upin: item.upin,
    mtype: item.mtype,
    land: item.land
  };
});

You can use map and destructing method for your requirement, you can include what properties you need. I did not see land property in your data.

const result = arr.map(({ upin, mtype }) => ({
  upin, mtype
}));

var arr =[{ id: 1,
mtype: "KIOSK PACKAGE",
part_fees: 200,
tb_bid_upins: 1,
tech_bid_flag: 0,
tot_media: 0,
type: "Road Stretch",
upin: "AMCADVT1415C0123",
upin_id: "2"
}, { 
id: 1,
mtype: "KIOSK PACKAGE",
part_fees: 200,
tb_bid_upins: 1,
tech_bid_flag: 0,
tot_media: 0,
type: "Road Stretch",
upin: "AMCADVT1415C0123",
upin_id: "2" }]

const result = arr.map(({ upin, mtype }) => ({
  upin, mtype
}));

console.log(result);

this is pure javascript and it has nothing to do with angular. you can use map function to transform arrays.

const arr2 = this.arr.map(el => ({upins: el.upins, mtyp: el.mtyp, land: el.land}));

The first answer is right. I only want to add that you can use map method for same goal. It's more comfortable for me:

const newData = data.map(x => {
    return {
        upin: x.upin,
        mtype: x.mtype,
        land: x.land
    };
});

Map will check each element in the array and return new object based on element properties.

Related