使用另一个数组中的值创建新数组

问题描述 投票:0回答:1

我简化了下面的数组以防止混淆。这是我到目前为止的进展...我尝试了各种方法来生成新的数组,但还没有成功。我什至在 Stack Overflow 上寻找解决方案。结果是准确的,但不幸的是,我只收到 fieldsArray 中的单个对象。我相信我目前的方法已经接近解决方案。如果您能提供任何帮助,我们将不胜感激。谢谢。

我有以下数组。

[
    {
        fileName: 'Home_AIT_Spraying-1_29062023.agdata',
        fileType: 'AgData',
        metadata: {
            tags: [
                {
                    type: 'Field',
                    value: 'Home',
                    uniqueId: null,
                },
                {
                    type: 'Farm',
                    value: 'OTF',
                    uniqueId: null,
                },
                {
                    type: 'Grower',
                    value: 'Jim Smith',
                    uniqueId: null,
                }
            ],
        },
    },
    {
        fileName: 'AIT_AIT_Spraying-1_30062023.agdata',
        fileType: 'AgData',
        metadata: {
            tags: [
                {
                    type: 'Field',
                    value: 'Oscar',
                    uniqueId: null,
                },
                {
                    type: 'Farm',
                    value: 'OTF',
                    uniqueId: null,
                },
                {
                    type: 'Grower',
                    value: 'Jasper Jones',
                    uniqueId: null,
                }
            ],
        },
    }
]

我希望输出如下所示:

[
    {
        Field: 'AIT',
        Farm: 'OTF',
        Grower: 'Jim Smith',
    },
    {
        Field: 'Oscar',
        Farm: 'OTF',
        Grower: 'Jasper Jones',
    },
];

我目前的解决方案:

const fieldsMetaArray = [] as [];

data.forEach((val, key) => {
    console.log('key', key);
    val.metadata.tags.map((tag) => {
        console.log(`key: ${tag.type} value: ${tag.value}`);
        fieldsMetaArray[tag.type] = tag.value;
    });
});

console.log(fieldsArray);

javascript arrays multidimensional-array key-value
1个回答
0
投票

您需要为 fieldsMetaArray 中的每个项目创建一个对象,而不是数组,然后将每个对象推入 fieldsMetaArray 中,而不是直接为其属性赋值。

由于您希望输出仅包含“Field”、“Farm”和“Grower”,因此您应该在映射过程中过滤掉其他类型。

const fieldsMetaArray = [];

data.forEach((val) => {
    const fieldMeta = {}; // Create a new object for each item
    val.metadata.tags.forEach((tag) => {
        // Check if the tag type is 'Field', 'Farm', or 'Grower'
        if (['Field', 'Farm', 'Grower'].includes(tag.type)) {
            // Assign the value to the corresponding property in the object
            fieldMeta[tag.type] = tag.value;
        }
    });
    // Push the object into the fieldsMetaArray
    fieldsMetaArray.push(fieldMeta);
});

console.log(fieldsMetaArray);
© www.soinside.com 2019 - 2024. All rights reserved.