B
B
BKaiyrbekov2020-04-29 13:56:08
JavaScript
BKaiyrbekov, 2020-04-29 13:56:08

How to simplify javascript code[recursion]?

I wrote some shitty code, how to simplify this code?
there is an object

object = {
    article: 10,
    blog: 5,
    officialclarification: 1,
    qa: 1,
    questionanswer: 2,
    ....
}

there is another array
array = [
    {
        links: [
            { ... parentType: 'blog' },
            { ... parentType: 'article' },
            { ... parentType: 'officialclarification' },
            { ... parentType: 'questionanswer' },
            { ... parentType: 'opendialog' },
        ]
    },
   ....
]

now my function
function searchParentType(data, key, value) {
    if (Array.isArray(data)) {
        data.forEach(item => searchParentType(item, key, value))
    } else {
        if (data.parentType === key) data.count = value
    }
}
function changeCount() {
    Object.entries(object).forEach(([key, value]) => {
        array.forEach(item => searchParentType(item.links, key, value))
    })
}

result
array = [
    {
        links: [
            { ... parentType: 'blog', count: 5 },
            { ... parentType: 'article', count: 10},
            { ... parentType: 'officialclarification', count: 1 },
            { ... parentType: 'questionanswer', count: 2 },
            { ... parentType: 'opendialog'},
        ]
    },
   ....
]


p/s: the main disadvantage in my code is that the loop continues in my code even if this condition (data.parentType === key) is met...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BKaiyrbekov, 2020-04-29
@BKaiyrbekov

Well, I simplified it like that .... and I myself am satisfied)

array.forEach(groupLinks => { 
    groupLinks.links.forEach(itemLink => { 
        if (itemLink.parentType in object) itemLink.count = object[itemLink.parentType]
    })
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question