gpt4 book ai didi

javascript - 使用javascript将一组对象转换为一组新的对象?

转载 作者:行者123 更新时间:2023-11-28 18:05:03 26 4
gpt4 key购买 nike

这个问题已经以多种不同的形式被提出,但我无法将它们拼凑起来以实现我正在寻找的结果。所以,很抱歉重复了这些重复项...

我想要做的是采用这样的数组:

[
0: {
2014: "6",
2015: "19",
2016: "3",
2017: "12",
Name: "Jerry"
},
1: {
2014: "16",
2015: "9",
2016: "",
2017: "16",
Name: "Bill"
},
2: {
2014: "",
2015: "2",
2016: "43",
2017: "7",
Name: "Grace"
}
]

像这样:

{
"years": {
"2014": {
"Jerry": 6,
"Bill": 16,
"Grace": ""
},
"2015": {
"Jerry": 19,
"Bill": 9,
"Grace": 2
},
"2016": {
"Jerry": 3,
"Bill": "",
"Grace": 43
},
"2017": {
"Jerry": 12,
"Bill": 16,
"Grace": 7
}
}
}

在尝试、删除、重复、重复...之后我仍然拥有一些代码:

仅供引用 - 数据来自从 D3.js csv() 加载的 CSV 文件

let loadData = () => {
return d3.csv(dataFile, function cb (err, d) {
if (err) throw err;
return d;
});
};

loadData().get((err, n) => {
if (err) throw err;

let years = [];

years.push(Object.keys(n[0]));

years = _.flatten(years);
years.splice(-1, 1);


console.log(n[0]);

n.map((x) => {
console.log(Object.keys(x[0]));
});

});

最佳答案

您可以使用“reduce”来实现此目的。

var data = [{
2014: "6",
2015: "19",
2016: "3",
2017: "12",
Name: "Jerry"
}, {
2014: "16",
2015: "9",
2016: "",
2017: "16",
Name: "Bill"
}, {
2014: "",
2015: "2",
2016: "43",
2017: "7",
Name: "Grace"
}];

data = data.reduce(function(pre, v) {

for (var i in v) {
if (i === 'Name') {
continue;
}
if (!pre[i]) {
pre[i] = {};
};

pre[i][v.Name] = v[i];

}
return pre;
}, {});
data = {
years: data
};
console.log(data);

关于javascript - 使用javascript将一组对象转换为一组新的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42859086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com