提问人:grabrep gg 提问时间:8/30/2023 更新时间:8/30/2023 访问量:59
将多个 Array 对象行转换为一行,按键分组
Convert multiple Array object rows to one row, group by key
问:
我有下面的数组对象
var dataarray = [{Region: 'Asia', Total: '0.50'},
{Region: 'America', Total: '1.50'},
{Region: 'Middle East', Total: '1.50'}]
我想像波纹管一样转换它
var convertarray = [{'Asia' : '0.50', 'America' : '1.50', 'Middle East' : '1.50'}]
我尝试了波纹管方式,但即使按区域摸索,它也会创建多行
var result = [];
dataarray.forEach(entry => {
let existingCountry = result.find(Region => Region.Region === entry.Region);
if (existingCountry) {
existingCountry[entry.Region] = entry.Total;
} else {
let newCountry = { "Region": entry.Region };
newCountry[entry.Region] = entry.Total;
result.push(newCountry);
}
});
var alldata = Array.from(new Set(dataarray.map(entry => entry.Region)));
result.forEach(Region => {
alldata.forEach(month => {
if (!Region.hasOwnProperty(month)) {
Region[month] = 0;
}
});
});
存档所需结果的任何其他方法
答:
-2赞
TriveeCodez
8/30/2023
#1
要将多个数组对象行转换为按键分组的单行,可以使用 JavaScript 中的方法。下面是如何实现预期结果的示例:reduce
var dataarray = [
{ Region: 'Asia', Total: '0.50' },
{ Region: 'America', Total: '1.50' },
{ Region: 'Middle East', Total: '1.50' }
];
var convertarray = dataarray.reduce((acc, entry) => {
acc[entry.Region] = entry.Total;
return acc;
}, {});
console.log(convertarray);
这将输出:
{
'Asia': '0.50',
'America': '1.50',
'Middle East': '1.50'
}
在上面的代码中,我们使用该方法遍历并在对象中累积所需的结果。对于每个条目,我们将值分配给对象中的相应键。reduce
dataarray
convertarray
Total
Region
convertarray
这种方法消除了对现有国家/地区进行额外循环和检查的需要。该方法简化了代码,并提供了更简洁的解决方案。reduce
我希望这会有所帮助!如果您有任何其他问题,请告诉我。
评论
0赞
grabrep gg
8/30/2023
这也有效,谢谢
1赞
Mike 'Pomax' Kamermans
8/30/2023
#2
看起来您所做的只是将数组中的每个对象映射到 ,您可以通过利用 JS 的属性名称括号表示法在单个步骤中完成:{ Region : somekey, Total: value }
{ somekey: value }
const data = [
{ region: 'Asia', total: '0.50'},
{ region: 'America', total: '1.50'},
{ region: 'Middle East', total: '1.50'}
];
const remapped = data.map(e => ({[e.region]: e.total}));
console.log(remapped);
评论