简体   繁体   中英

Array map and skip undefined dynamic object properties

Trying to figure out how to create dynamic object in 'map' function. Mapping is based on large json object and I am trying to find a way to reduce final array size. Ideally to not add properties that have undefined values. Ie if 'offst: undefined', then skip this property but add other that have proper int value. Is it possible to do something like this without looping through array again? Array has over 150k entries so performance hit would be significant.

this.mapData = this.mapData
                .map((e) => ({
                    p: e.p,
                    lat: e.lat,
                    lng: e.lng,
                    y: Object.keys(e.values)[0],
                    ct: Object.values(e.values)[0].ct, // add ct: only if not undefined
                    cp: Object.values(e.values)[0].cp,
                    w: Object.values(e.values)[0].wp,
                    offst: Object.values(e.values)[0].offst,
                    onst: Object.values(e.values)[0].onst,
                    ertn: Object.values(e.values)[0].ertn,
                    ertl: Object.values(e.values)[0].ertl,
                    dst: Object.values(e.values)[0].dst,
                    ft: Object.values(e.values)[0].ft,
                }))
                .filter((item) => item.chargersTotal !== 0);

            return this.mapData;

Exmaple json data:

[
   {
      "p":"BA1 2RU",
      "lat":"51.38934",
      "lng":"-2.364467",
      "values":{
         "2019":{
            "ct":0.0
            "dst":5.0
            "onst":1.0
         }
      }
   },
   {
      "p":"BA10 0AA",
      "lat":"51.112275",
      "lng":"-2.453865",
      "values":{
         "2019":{
            "offst":1.0,
            "ct":1.0
         }
      }
   },
   {
      "p":"BA10 0AB",
      "lat":"51.112463",
      "lng":"-2.454067",
      "values":{
         "2019":{
            "ct":0.0
         }
      }
   }
]

Use ellipsis to merge Object.values(e.values)[0] into the object you're returning. Then it will only merge in the properties that exist.

 this.mapData = this.mapData.map((e) => { let firstKey = Object.keys(e.values)[0]; let firstVal = e.values[firstKey]; return { p: ep, lat: e.lat, lng: e.lng, y: firstKey, ...firstVal }; }).filter((item) => item.chargersTotal;== 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM