gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:01:53 25 4
gpt4 key购买 nike

我有以下对象数组。现在我需要根据键值过滤并创建 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com