Issue
I want to reformat the existing array, how can i do it using Javascript or typescript
first array
pdfData: [
{
Id: 1,
path:'https//path/pdf1'
},
{
Id: 1,
path:'https//path/pdf2'
},
{
Id: 2,
path:'https//path/pdf1'
},
{
Id: 2,
path:'https//path/pdf2'
},
]
I want to convert this array to following one
data: [
{
Id: 1,
links:['https//path/pdf1','https//path/pdf2']
},
{
Id: 2,
links:['https//path/pdf1','https//path/pdf2']
},
]
Solution
You were asking about Typescript or Javascript - here's the Typescript version:
// Typescript version
const pdfData = [
{
Id: 1,
path:'https//path/pdf1'
},
{
Id: 1,
path:'https//path/pdf2'
},
{
Id: 2,
path:'https//path/pdf1'
},
{
Id: 2,
path:'https//path/pdf2'
},
]
interface TransformedDataItem {
Id: number,
links: string[]
}
const result = [] as TransformedDataItem[];
for (const item of pdfData) {
const existing = result.find(it => it.Id === item.Id);
if (existing) {
existing.links.push(item.path)
} else {
result.push({
Id: item.Id,
links: [item.path]
})
}
}
Answered By - Aadmaa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.