我是Javascript的新手,我遇到了一个词典列表问题。我有一个像这样的对象:
(df.start.shift(-1)==df.end).shift().ne(True).cumsum()
Out[434]:
0 1
1 1
2 1
3 2
4 2
5 2
dtype: int32
我希望将其转换为一个新的值,其中值Exports和Imports为两个不同的列,其下方的相应支出。像这样:
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"}
有谁知道怎么做?提前谢谢。
答案 0 :(得分:0)
这对reduce来说是个不错的选择:
let arry = [{
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"
}
]
let result = arry.reduce((r, v) => r.concat([{
Year: v.Year,
[v.category]: v.expenditure
}]), [])
console.log(result)

答案 1 :(得分:0)
const output = input.map(({Year, expenditure, category}) => ({Year, [category]: expenditure }));
只需破坏每个物体并构建一个新物体。您还可以使用rest / spread包含新对象中的所有其他属性:
const output = input.map(({expenditure, category, ...rest}) => ({[category]: expenditure, ...rest }));