【问题标题】:How do I convert an array of objects to an array including only one property's values?如何将对象数组转换为仅包含一个属性值的数组?
【发布时间】:2023-01-14 08:29:44
【问题描述】:

我正在尝试使用 .includes( ) 数组方法来检查某个项目是否在我的 JSON 文件中。到目前为止,我已经连接到数据库(使用 JSON 服务器 npm 插件)并检索了对象数组,并将它们存储在变量“fetchedData”中。现在,我知道 .includes() 将数组作为第一个参数并在数组中搜索第二个参数。如何将此对象数组转换为仅包含名称属性值的数组? .includes( ) 是这样工作的吗?

这是 JSON 文件:

  "savedexercises": [
    {
      "name": "all fours squad stretch",
      "target": "quads",
      "gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/1512.gif",
      "id": 1
    },
    {
      "name": "ankle circles",
      "target": "calves",
      "gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/1368.gif",
      "id": 2
    },
    {
      "name": "arm slingers hanging bent knee legs",
      "target": "abs",
      "gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/2355.gif",
      "id": 3
    }
  ]
}

我只是想访问所有名称属性值,然后将它们存储到一个数组中。

【问题讨论】:

  • 你想要一个 { name: value } 的对象数组吗?

标签: javascript reactjs json fetch


【解决方案1】:

您可以过滤和映射以查找特定键的所有值并将其转换为对象数组或任何形式。 includes 只会告诉您是否存在这样的密钥。参考下面的代码

  const createArraybasedOnkey= (key) => {
    console.log(
      obj.savedexercises
        .filter((x) => x[key])
        ?.map((x) => {
          return { [key]: x[key] };
        })
    );
  };

代码沙箱:https://codesandbox.io/s/pedantic-rain-u1t9th?file=/src/App.js:625-817

【讨论】:

    【解决方案2】:

    使用array.map()。例如:

    const exerciseNames = savedexercises.map(exercise => exercise.name)
    // Expected output:
    // ["all fours squad stretch", "ankle circles",
    //  "arm slingers hanging bent knee legs"]
    
    // Now you can check if the exerciseNames includes a certain exercise:
    console.log(exerciseNames.includes("all fours squad stretch"))
    // Expected output: true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      相关资源
      最近更新 更多