array数组处理

131 阅读2分钟

要将给定的数组转换为新的格式,可以使用JavaScript中的数组和对象方法来重构数据

const originalArray = [ { key: 'recharge', value: 'true', operator: 'true' }, { key: 'WJ', value: '1', operator: 'between', maxValue: '99' }, { key: 'WJ', value: '20', operator: 'le_equal' }, { key: 'JK', value: 'ces', operator: 'is_not' } ]; const newArray = originalArray.reduce((acc, item) => { // 查找当前key是否已经存在于累加器acc中 const existingGroup = acc.find(group => Object.keys(group)[0] === item.key); if (existingGroup) { // 如果存在,将当前项添加到对应的数组中 existingGroup[item.key].push(item); } else { // 如果不存在,创建一个新的组并添加到累加器中 const newGroup = {}; newGroup[item.key] = [item]; acc.push(newGroup); } return acc; }, []); console.log(newArray);

判断数组|多数组 中每一项的key和icon是否为空

arr.forEach((subArr, subArrIndex) => {
    subArr.forEach((obj, objIndex) => {
      const keys = Object.keys(obj);
      const emptyKeys = keys.filter(key => key.endsWith('Odds') || key.endsWith('Probability')).some(key => obj[key] === '');
      if (emptyKeys) {
        ElMessage.error(`第 ${subArrIndex + 8}行,有空值`);
      }
    });
  });
const areAllItemsValid = list.formImage.every(item => {
    return item.key && item.icon && item.key.trim() !== '' && item.icon.trim() !== '';
  });

reduce 函数可以将数组中的每个元素合并成一个单一的结果

使用 `Object.entries()` 方法配合 `map()` 方法。`Object.entries(obj)` 会返回一个给定对象自身可枚举属性的键值对数组,然后您可以通过 `map()` 方法将每个键值对映射回原始数组的形式。
const arr = Object.entries(obj).map(([key, icon]) => { return { key: key, icon: icon }; });
const obj = arr.reduce((accumulator, currentValue) => { accumulator[currentValue.key] = currentValue.icon; return accumulator; }, {});

数组每一项填充

const computedRowsData = computed(() => {
  const fromData = formParams.value[gameDataPage.radio][gameDataPage.highsRow - 8];
  const newData = rowsDataToArr(gameDataPage.radio, gameDataPage.highsRow);
  if (fromData?.length > 0) {
    newData.forEach(item => {
      Object.keys(item).forEach(key => {
        if (Array.isArray(fromData)) {
          const fromItem = fromData.find(from => from && from[key] !== undefined);
          if (fromItem) {
            item[key] = fromItem[key];
          }
        }
      });
    });
  }
  return newData;
});

const createAObject = row => {
  const aObject = {};
  for (let i = 1; i <= row + 1; i++) {
    aObject[`a${i}Odds`] = '';
    aObject[`a${i}Probability`] = '';
  }
  return aObject;
};
//转换值
const transformData = data => {
  const result = {};
  for (const key of Object.keys(data)) {
    result[key] = data[key]
      .map((array, index) => {
        if (array) {
          const a = array.reduce((acc, item) => {
            return { ...acc, ...item };
          }, {});
          return { row: index + 1, a };
        }
        return null;
      })
      .filter(item => item !== null);
  }

  return result;
};

const ToArray = data => {
  return [
    Object.keys(data).reduce((acc, key) => {
      acc[key] = data[key] === null ? '' : data[key];
      return acc;
    }, {})
  ];
};

计算数组中 每一项的probability×odds的总和

let sum = low.reduce((total, item) => total + item.probability * item.odds, 0); console.log(sum);

判断这个数组中的probability和odds是否有空的

要检查数组中的probabilityodds字段是否有空值,你可以使用Array.prototype.some方法,它会检查数组中是否有至少一个元素满足提供的测试函数。在这个例子中,测试函数会检查probabilityodds字段是否为空。如果有任何一个元素满足这个条件,some方法会立即返回true。否则,它会返回false

   //判断数组中有空项
    export const hasEmptyFields = (arr: Array<{ [key: string]: any }>, field1: string, field2: string): boolean => {
      const result = arr.some(item => item[field1] === '' || item[field2] === '');
      return result;
  }
let hasEmptyFields = low.some(item => item.probability === '' || item.odds === '');
if (hasEmptyFields) { console.log('Some items have empty probability or odds'); }

将数组中所有value的值转成字符串

arr.map(item => item.id).join(', ');

数去去重

let myArray = [1, 2, 2, 3, 3, 3]; let uniqueArray = [...new Set(myArray)]; console.log(uniqueArray); // [1, 2, 3]
const uniqueArray = ArrayData.filter((v, i, a) => a.findIndex(t => (t.fullPath === v.fullPath)));

通过指定条件查找数据

const today = dayjs().format('YYYY-MM-DD');
  const yesterday = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
  const todayData = res.data.find(item => item.dateTime === today);
  const yesterdayData = res.data.find(item => item.dateTime === yesterday);

遍历数组 找到id与数组中的id匹配的一项的name

let item = array.find(obj => obj.id === targetId);

遍历数组 获取数组中某一key的集合

# let keyValues = array.map(obj => obj.key);

对数组排序 已数组中的时间timePeriod(格式为2023-10-08 05:10:00)排序

array.sort(function(a, b) { return new Date(a.timePeriod) - new Date(b.timePeriod); });

去掉数组中successRate的百分号

array.forEach(function(item) { item.successRate = item.successRate.replace('%', ''); });