Answer the question
In order to leave comments, you need to log in
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,
....
}
array = [
{
links: [
{ ... parentType: 'blog' },
{ ... parentType: 'article' },
{ ... parentType: 'officialclarification' },
{ ... parentType: 'questionanswer' },
{ ... parentType: 'opendialog' },
]
},
....
]
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))
})
}
array = [
{
links: [
{ ... parentType: 'blog', count: 5 },
{ ... parentType: 'article', count: 10},
{ ... parentType: 'officialclarification', count: 1 },
{ ... parentType: 'questionanswer', count: 2 },
{ ... parentType: 'opendialog'},
]
},
....
]
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question