Search code examples
javascriptarraystypescriptecmascript-6typescript-typings

Convert specific property from Record into Array in Typescript/Javascript


Need to convert Record Type in Typescript/Javascript to Array with specific property

const store: Record<ProductID, ProductObject> = {
        'france': productObject:{
                                 present: 'in_stock',
                                 amount: 23,                            
                                },
            'uk': productObject:{
                                 present: 'in_stock',
                                 amount: 20,                            
                                },
         'japan': productObject:{
                                 present: 'no_stock',
                                 amount: 0,                         
                                },                      
    }
    
    

Output: Creating New Array. Adding new key as 'country' & take only 'amount' property from store Record type.

const newArrayFromRecord = [
                            {country: 'france', amount: 23},
                            {country: 'uk', amount: 20}
                            {country: 'japan', amount: 0}
                           ]

I have tried with Object.entries() and then pushing in Array. But all require unnecessary code. Is there any efficient way to do..


Solution

  • This is one possible way to achieve the objective:

      Object.entries(store).map(([k, v]) => ({
        country: k,
        amount: v.amount
      }))
    

    Code Snippet using JS:

    const store = {
      'france': {
        present: 'in_stock',
        amount: 23,
      },
      'uk': {
        present: 'in_stock',
        amount: 20,
      },
      'japan': {
        present: 'no_stock',
        amount: 0,
      },
    };
    
    console.log(
      'result: ',
      Object.entries(store).map(([k, v]) => ({
        country: k,
        amount: v.amount
      }))
    );

    And, here's a TypeScript Playground link.