首页 > 解决方案 > 在对象数组上跳过地图

问题描述

我不知道为什么我的地图没有解析。它以某种方式跳过了我的地图,尽管countriesAtoH它向我显示它确实有一个对象数组但是当我尝试映射它时,它就像它没有映射它,因为我不能在地图中放置断点,而地图最终是没有被调用。意思是我的长度为 0options

const countries = {
  Afghanistan: {
    countryId: 0,
      name: "Afghanistan"
    },
    Albania: {
      countryId: 1,
      name: "USA"
    },
    Algeria: {
      countryId: 99,
      name: "Canada"
    }
}


export const countryOptions = () => {
  let countriesAtoH = [];
  Object.keys(countries).forEach((c) => {
    if (countries[c].countryId <= 97) {
      countriesAtoH[c] = countries[c];
    }
  });

  const options = countriesAtoH.map(country => {
    const c = {
      text: {
        type: "plain_text",
        text: country.name,
      },
      value: country.countryId
    }
      return c;
    });

  return options;
}                   

在此处输入图像描述

标签: javascript

解决方案


你有问题countriesAtoH[c] = countries[c]

的类型countriesAtoHarray索引应该是数字,并且您将c值(字符串)值分配为countriesAtoH数组上的索引。

因此,它不起作用。最好设置countriesAtoH = {}为对象并用于Object.values(countriesAtoH)获取options变量。

const countries = {
  Afghanistan: {
    countryId: 0,
    name: "Afghanistan"
  },
  Albania: {
    countryId: 1,
    name: "USA"
  },
  Algeria: {
    countryId: 99,
    name: "Canada"
  }
}

const countryOptions = () => {
  let countriesAtoH = {};
  Object.keys(countries).forEach((c) => {
    if (countries[c].countryId <= 97) {
      countriesAtoH[c] = countries[c];
    }
  });

  const options = Object.values(countriesAtoH).map((country) => {
    const c = {
      text: {
        type: "plain_text",
        text: country.name,
      },
      value: country.countryId
    }
    return c;
  });

  return options;
}

console.log(countryOptions());

简单地说,您可以使用Array.prototype.filterandArray.prototype.map来获取options.

const countries = {
  Afghanistan: {
    countryId: 0,
    name: "Afghanistan"
  },
  Albania: {
    countryId: 1,
    name: "USA"
  },
  Algeria: {
    countryId: 99,
    name: "Canada"
  }
}

const countryOptions = () => {
  const options = Object.values(countries).filter(({ countryId }) => countryId <= 97).map((item) => ({
    text: {
      type: "plain_text",
      text: item.name
    },
    value: item.countryId
  }));
  return options;
}

console.log(countryOptions());


推荐阅读