javascript - 根据键过滤对象数组的子集

标签 javascript typescript

我有以下对象数组。现在我需要根据键值过滤并创建 3 个单独的对象数组。

"data": [
{
  "BaseId": 1,
  "BaseDesc": "18 BHC Baseline",
  "StressId": 5,
  "StressDesc": "Desc 1",
  "bopId": 8,
  "bopDesc": "BOP Desc 1",
},
{
  "BaseId": 1,
  "BaseDesc": "Baseline 2",
  "StressId": 2,
  "StressDesc": "Desc 12",
  "bopId": 8,
  "bopDesc": "BOP Desc 2"
},
{
  "BaseId": 2,
  "BaseDesc": "Baseline 3",
  "StressId": 7,
  "StressDesc": "Desc 3",
  "bopId": 10,
  "bopDesc": "BOP Desc 3"
}

]

现在我需要过滤它并创建 3 个单独的对象数组,以便:

1. BaseData Array Obj


"baseData": [
{
  "BaseId": 1,
  "BaseDesc": "18 BHC Baseline"
},
{
  "BaseId": 1,
  "BaseDesc": "Baseline 2"
},
{
  "BaseId": 2,
      "BaseDesc": "Baseline 3"
    }
  ]
  • 应力数组对象:

        "data": [
        {
          "StressId": 5,
          "StressDesc": "Desc 1"
        },
        {
          "StressId": 2,
          "StressDesc": "Desc 12"
        },
        {
          "StressId": 7,
          "StressDesc": "Desc 3"
        }
      ]
    
  • 类似地,bop 数据的第三个对象。因此,如果我的实际数组的键中包含“base*”,那么我需要过滤并添加到 bop 数组,并且其他两个对象数组也采用相同的逻辑。

    有人可以指导我如何实现这一目标吗?

    最佳答案

    怎么样:

    const data = [
      {
        BaseId: 1,
        BaseDesc: "18 BHC Baseline",
        StressId: 5,
        StressDesc: "Desc 1",
        bopId: 8,
        bopDesc: "BOP Desc 1"
      },
      {
        BaseId: 1,
        BaseDesc: "Baseline 2",
        StressId: 2,
        StressDesc: "Desc 12",
        bopId: 8,
        bopDesc: "BOP Desc 2"
      },
      {
        BaseId: 2,
        BaseDesc: "Baseline 3",
        StressId: 7,
        StressDesc: "Desc 3",
        bopId: 10,
        bopDesc: "BOP Desc 3"
      }
    ];
    
    const pickSpecifiedProperties = (startingPropString, arrayOfObjects) =>
      arrayOfObjects.map(obj => {
        const targetKeys = Object.keys(obj).filter(
          keyName =>
            keyName.toLowerCase().indexOf(startingPropString.toLowerCase()) === 0
        );
        return targetKeys.reduce((data, keyName) => {
          const newProperty = { [keyName]: obj[keyName] };
          return { ...data, ...newProperty };
        }, {});
      });
    
    const baseData = pickSpecifiedProperties("Base", data);
    const stressData = pickSpecifiedProperties("Stress", data);
    const bopData = pickSpecifiedProperties("bop", data);
    
    console.log({ baseData, stressData, bopData });
    

    关于javascript - 根据键过滤对象数组的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55131705/

    相关文章:

    Angular 2上下滑动动画

    node.js - 类型 'string[][]' 不可分配给类型 'string[]'

    angular - 显示单个 Observable,而不是数组

    typescript 。如何在一个模块中导出两个类(在单独的文件中)?

    二进制字符串的 typescript 类型

    javascript - Angular : Creating questions using a directive

    javascript - Bootstrap-Vue 坏了吗?

    javascript - 软件设计 - 两个类之间的交互

    javascript - 删除托管页面上的表单部分

    javascript - 如何在 API 调用中传递 key 作为授权 header