通过嵌套对象重新循环时保留原始密钥 [英] Keep original key when re-looping through nested object

查看:150
本文介绍了通过嵌套对象重新循环时保留原始密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有子对象和数组的嵌套对象。像这样的东西:

I've got a nested object with child objects and arrays. Something like this:

const documents = {
    invoice: {
        documentID: '_e4564',
        displayName: '2019-02-03',
        url: 'https://www.urltoinvoice.com'
    },

    conditions: {
        documentID: '_e9365',
        displayName: 'Conditions company x',
        url: 'https://www.urltoconditions.com'
    },

    reminders: [
        {
            documentID: '_e4364',
            displayName: 'First reminder',
            url: 'https://www.urltofirstreminder.com'
        },
        {
            documentID: '_e0254',
            displayName: 'Second reminder',
            url: 'https://www.urltosecondreminder.com'
        },
    ]
}

我正在尝试创建一个新的数组选择框中使用的对象。
子对象需要相同的属性,但具有基于文档类型的更新的displayName。因此,例如 reminder:首先提醒

I'm trying to create a new array of objects to use in a select box. The child objects need the same properties but with an updated displayName based on the document type. So, for example, reminder: First reminder .

当前,这是我的代码:

const newArray = [];
this.addDocumentToArray(documents, newArray);

和addDocumentToArray函数:

and the addDocumentToArray function:

addDocumentToArray = (documents, arr) => {
    Object.entries(documents).forEach(([key, val]) => {
        if (Array.isArray(val)) {
            this.addDocumentToArray(val, arr);
        } else {
            arr.push({ documentID: val.documentID, displayName: `${key}: ${val.displayName}` });
        }
    });
}

此时的输出是一个看起来像这样的数组:

The output at this point is an array that looks like this:

0: {documentID: "_e4564", displayName: "invoice: 2019-02-03"}
1: {documentID: "_e9365", displayName: "conditions: Conditions company x"}
2: {documentID: "_e4364", displayName: "0: First reminder"}
3: {documentID: "_e0254", displayName: "1: Second reminder"}

几乎可以,但提醒的键是 0 1 。如何获得提醒(或提醒)作为键?

Almost ok but the key of the reminders is 0 and 1. How can I get reminder (or reminders) as key?

推荐答案

您可以将第三个可选参数添加到功能labelKey。仅当您的值是数组且要使用该值作为其他部分的键时才传递该参数

You can add third optional parameter to function labelKey. You are passing that parameter only if your value is array and it will use that value as key in else part

addDocumentToArray = (documents, arr, labelKey) => {
        Object.entries(documents).forEach(([key, val]) => {
            if (Array.isArray(val)) {
                this.addDocumentToArray(val, arr, key);
            } else {
                arr.push({ documentID: val.documentID, displayName: `${labelKey || key}: ${val.displayName}` });
            }
        });
    }

这篇关于通过嵌套对象重新循环时保留原始密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆