Skip to content Skip to sidebar Skip to footer

Keep Original Key When Re-looping Through Nested Object

I've got a nested object with child objects and arrays. Something like this: const documents = { invoice: { documentID: '_e4564', displayName: '2019-02-03',

Solution 1:

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}` });
            }
        });
    }

Solution 2:

I really like chriss' answer, so I'll try to write an alternative:

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

Post a Comment for "Keep Original Key When Re-looping Through Nested Object"