首页 > 解决方案 > 从对象数组中删除当前索引

问题描述

我正在尝试删除与我的 if 语句匹配的对象

我的数组:

[
   TextRow {
     id: 4,
     user_gender: 'Male',
     user_tags: '[]',
     user_birth: 26,
     user_lat: '34.03569255690516',
     user_lng: '-6.828115666526287',
     user_current_occupancy: 'None',
     user_biography: null,
     set_from_map: 1,
     info_verified: 0
   },
   TextRow {
     id: 5,
     user_gender: 'Male',
     user_relationship: 'Single',
     user_tags: '[]',
     user_birth: 19,
     user_lat: '32.8811',
     user_lng: '-6.9063',
     user_current_occupancy: 'None',
     user_biography: null,
     set_from_map: 1,
     info_verified: 0
   }
 ]

这是一个代码片段:在距离函数中,我正在计算用户和其他用户之间的目的地,我将它们放在数据数组中

data.map((value, i) => {

      const destination = parseFloat(
        distance(lat, long, value.user_lat, value.user_lng).toFixed(2)
      );
      // age_range is an array that have the range of age for example[16,26]
      if (
        destination > location_range ||
        value.user_birth < age_range[0] ||
        value.user_birth > age_range[1]
      ) {
        data.splice(i, 1);
        i = i - 1;
      } else value.destination = destination;
    });

它没有达到我想要的效果,提前谢谢你

标签: javascript

解决方案


const data = newData.filter(el => {
const destination = parseFloat(
distance(lat, long, el.user_lat, el.user_lng).toFixed(2)
);
console.log(
destination > location_range ||
el.user_birth < age_range[0] ||
el.user_birth > age_range[1]
);
return !(
destination > location_range ||
el.user_birth < age_range[0] ||
el.user_birth > age_range[1]
);
});
data.forEach(el => {
const destination = parseFloat(
distance(lat, long, el.user_lat, el.user_lng).toFixed(2)
);
el.destination = destination;
});

推荐阅读