Home > Mobile >  Convert specific property form Record into Array in Typescript/Javascript
Convert specific property form Record into Array in Typescript/Javascript

Time:04-17

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..

CodePudding user response:

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.

CodePudding user response:

You could just loop over the store object using a for in loop.

Or mapping it with Object.keys.

Aside from that I don't think there is really a more "efficient" solution.

const store = {
    france: {
        present: "in_stock",
        amount: 23,
    },
    uk: {
        present: "in_stock",
        amount: 20,
    },
    japan: {
        present: "no_stock",
        amount: 0,
    },
};

const result = [];
for (const country in store) {
    result.push({ country, amount: store[country].amount });
}

const result_2 = Object.keys(store).map((country) => ({
    country,
    amount: store[country].amount,
}));

console.log(result);
console.log(result_2);

  • Related