转换对象数组的结构

时间:2021-02-09 11:18:03

标签: javascript arrays json

我有这个对象数组:

[{
  "Germany": "text",
  "Brazil": "50.00"
}, {
  "Germany": "1000.00",
  "Brazil": "1100.00"
}, {
  "Germany": "999999999",
  "Brazil": "9999999",
  "France": "12"
}]

我想将其转换为以下结构:

[{
  "name": "Germany",
  "value": 999999999
}, {
  "name": "Brazil",
  "value": 999999999
}, {
  "name": "France",
  "value": 12
}]

在第二个对象中,我们对第一个对象中的每个键使用较高的值。

编辑:值也可以是文本,例如 "Germany": "text" ,在这种情况下应该忽略该值。我在上面的第一个对象中添加了这种情况。

2 个答案:

答案 0 :(得分:4)

您可以使用 reduce 函数来获得预期的输出。在reduce里面,你可以取当前对象的Object.entries,以便按国家名称分组。

const arr = [{
  "Germany": "100.00",
  "Brazil": "50.00"
}, {
  "Germany": "1000.00",
  "Brazil": "1100.00"
}, {
  "Germany": "999999999",
  "Brazil": "9999999",
  "France": "12"
}];

const result = Object.values(arr.reduce((a,e)=>{
    Object.entries(e).forEach(([name, value])=>{
        a[name] ??= {name, value:0};
        a[name].value = a[name].value>value ? a[name].value : value
    });
    return a;
},{}));

console.log(result);

答案 1 :(得分:3)

您可以使用 .reduce 迭代对象,使用 .forEach 迭代每个对象条目:

const data = [
  { "Germany": "100.00", "Brazil": "50.00" }, 
  { "Germany": "1000.00", "Brazil": "1100.00" }, 
  { "Germany": "text", "Brazil": "9999999", "France": "12" }
];

const res = Object.values(data.reduce((acc,item) => {
  Object.entries(item).forEach(([name,value]) => {
    if(!isNaN(value)) {
      const prev = acc[name];
      if(!prev) acc[name] = { name,value } ;
      else if(prev.value < value) prev.value = value;
    }
  });
  return acc;
}, {}));

console.log(res);

相关问题