Home > front end >  How to create new array from existing array with different structure
How to create new array from existing array with different structure

Time:12-29

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']
         },

  ]

CodePudding user response:

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]
        })
    }
}

CodePudding user response:

This ought to do it:

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'
    },
]



const result = [];

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]
        })
    }
}

CodePudding user response:

Another one, kind of ES6 style solution

const data = [{Id: 1, path:'https//path/pdf1'},{ Id: 1, path:'https//path/pdf2'},{ Id: 2, path:'https//path/pdf1'},{ Id: 2, path:'https//path/pdf2'}];

const result = Object.values(data.reduce((acc, { Id, path }) => ({
  ...acc, 
  [Id]: acc[Id] 
    ? { ...acc[Id], links: [...acc[Id].links, path] }
    : { Id, links: [path] },
}), {}));

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

  • Related