需要将 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,
},
}
输出:创建新数组。将新密钥添加为 'country' 并仅从存储记录类型中获取 'amount' 属性。
const newArrayFromRecord = [
{country: 'france', amount: 23},
{country: 'uk', amount: 20}
{country: 'japan', amount: 0}
]
我尝试过使用 Object.entries() 然后推入数组。但所有这些都需要不必要的代码。有什么有效的办法吗..
这是实现目标的一种可能方法:
Object.entries(store).map(([k, v]) => ({
country: k,
amount: v.amount
}))
使用 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
}))
);
而且,这是一个 TypeScript Playground 链接。
您可以使用
for in
循环遍历存储对象。
或用
Object.keys
进行映射。
除此之外,我认为确实没有更“有效”的解决方案。
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);
使用
Object.entries
和 destructuring
const data = {
'france': {
present: 'in_stock',
amount: 23,
},
'uk': {
present: 'in_stock',
amount: 20,
},
'japan': {
present: 'no_stock',
amount: 0,
},
};
const res = Object.entries(data).map(([country, { amount }]) => ({
country,
amount,
}));
console.log(res);