在 Typescript/Javascript 中将特定属性从记录转换为数组

Mik*_*ils 1 javascript arrays typescript ecmascript-6 typescript-typings

需要将 Typescript/Javascript 中的记录类型转换为具有特定属性的数组

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,                         
                                },                      
    }
    
    
Run Code Online (Sandbox Code Playgroud)

输出:创建新数组。添加新键作为“国家/地区”并仅从存储记录类型中获取“金额”属性。

const newArrayFromRecord = [
                            {country: 'france', amount: 23},
                            {country: 'uk', amount: 20}
                            {country: 'japan', amount: 0}
                           ]
Run Code Online (Sandbox Code Playgroud)

我尝试过使用Object.entries()然后推入数组。但所有这些都需要不必要的代码。有没有什么有效的办法..

jsN*_*00b 5

这是实现目标的一种可能方法:

  Object.entries(store).map(([k, v]) => ({
    country: k,
    amount: v.amount
  }))
Run Code Online (Sandbox Code Playgroud)

使用 JS 的代码片段:

  Object.entries(store).map(([k, v]) => ({
    country: k,
    amount: v.amount
  }))
Run Code Online (Sandbox Code Playgroud)

而且,这里有一个TypeScript Playground 链接