将类别转换为列名称

时间:2018-04-14 09:31:59

标签: javascript

我是Javascript的新手,我遇到了一个词典列表问题。我有一个像这样的对象:

0:{Year: "2007", expenditure: "314,448.7", category: "Exports"}
1:{Year: "2008", expenditure: "320,805.2", category: "Exports"}
2:{Year: "2007", expenditure: "314,448.7", category: "Imports"}
3:{Year: "2008", expenditure: "320,805.2", category: "Imports"}

我希望将其转换为一个新的值,其中值Exports和Imports为两个不同的列,其下方的相应支出。像这样:

0:{Year: "2007", Exports: "314,448.7", Imports: "314,448.7"}
1:{Year: "2008", Exports: "320,805.2", Imports: "320,805.2"}

有谁知道怎么做?提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用array#reduce根据Year累积对象。然后使用Object.values()提取所有值。



const arr = [{Year: "2007", expenditure: "314,448.7", category: "Exports"},{Year: "2008", expenditure: "320,805.2", category: "Exports"}, {Year: "2007", expenditure: "314,448.7", category: "Imports"},{Year: "2008", expenditure: "320,805.2", category: "Imports"}],
    result = Object.values(arr.reduce((r, {Year, expenditure, category}) => {
      r[Year] = r[Year] || {Year};
      r[Year][category] = expenditure;
      return r;
    },{}));
console.log(result);




答案 1 :(得分:0)

使用函数<div class="arrow_box"> <img src="https://upload.wikimedia.org/wikipedia/commons/3/30/Amazona_aestiva_-upper_body-8a_%281%29.jpg" class="user-image" alt=""> </div>根据类别累积。

&#13;
&#13;
Arra.prototype.reduce
&#13;
const arr = [{Year: "2007", expenditure: "314,448.7", category: "Exports"},{Year: "2008", expenditure: "320,805.2", category: "Exports"}, {Year: "2007", expenditure: "314,448.7", category: "Imports"},{Year: "2008", expenditure: "320,805.2", category: "Imports"}];
const result = Object.values(arr.reduce((a, e) => ((a[e.Year] || (a[e.Year] = { Year: e.Year }))[e.category] = e.expenditure, a), {}));

console.log(result);
&#13;
&#13;
&#13;