我有一个看起来像这样的JSON对象-
0: {"": "1", company_name: ".", yearMonth: "1977-01-01", cumulative_raised: "0", rank: "1"}
1: {"": "2", company_name: ".comDominio", yearMonth: "1977-01-01", cumulative_raised: "0", rank: "2"}
2: {"": "3", company_name: ".FOX Networks", yearMonth: "1977-01-01", cumulative_raised: "0", rank: "3"}
3: {"": "4", company_name: "'Rock' Your Paper", yearMonth: "1977-01-01", cumulative_raised: "0", rank: "4"}
4: {"": "5", company_name: "( caravelo (", yearMonth: "1977-01-01", cumulative_raised: "0", rank: "5"}
5: {"": "6", company_name: "[24]7", yearMonth: "1977-01-01", cumulative_raised: "0", rank: "6"}
我想创建一个JSON对象,该对象具有yearMonth,然后按公司排名列出其名称和筹集资金的信息。看起来像这样-
{1977-01-01: {…}, 1977-02-01: {…}, 1977-03-01: {…}, 1977-04-01: {…}, 1977-05-01: {…}, …}
1977-01-01:
1: {name: ".FOX Networks", rank: "1", cumulative_raised: "20000"}
2: {name: "Blockcar", rank: "2", cumulative_raised: "10000"}
3: {name: "CHerry", rank: "3", cumulative_raised: "5000"}
4: {name: "TreesSimple", rank: "4", cumulative_raised: "2000"}
1977-02-01:
1: {name: "Blockcar", rank: "1", cumulative_raised: "30000"}
2: {name: "CHerry", rank: "2", cumulative_raised: "22000"}
3: {name: "Soundbus", rank: "3", cumulative_raised: "9000"}
4: {name: "Hopscotch", rank: "4", cumulative_raised: "5000"}
1977-03-01:
1: {name: "Honey", rank: "1", cumulative_raised: "30000"}
2: {name: "MangaRu", rank: "2", cumulative_raised: "22000"}
3: {name: "Hoss", rank: "3", cumulative_raised: "9000"}
4: {name: "Bread", rank: "4", cumulative_raised: "5000"}
这是我正在尝试使用的代码-
d3.csv("amount-raised-month.csv", function(error, csvdata) {
if (error) throw error;
csvdata.forEach(function(d) {
companies[d.yearMonth] = {}
companies[d.yearMonth][d.rank] = {"rank": d.rank, "name": d.company_name, "raised": d.cumulative_raised}
}) })
问题在于此代码将覆盖而不是附加代码。最后,我只列出了每个月的最后一个排名。
{1977-01-01: {…}, 1977-02-01: {…}, 1977-03-01: {…}, 1977-04-01: {…}, 1977-05-01: {…}, …}
1977-01-01:
4: {name: "TreesSimple", rank: "4", cumulative_raised: "2000"}
1977-02-01:
4: {name: "Hopscotch", rank: "4", cumulative_raised: "5000"}
1977-03-01:
4: {name: "Bread", rank: "4", cumulative_raised: "5000"}
如何每次都附加新的JSON对象而不是覆盖?
答案 0 :(得分:2)
您正在用{}覆盖先前的对象:
companies[d.yearMonth] = {}
尝试以下方法:
companies[d.yearMonth] = companies[d.yearMonth] || {};
或使用if语句:
if (!companies[d.yearMonth]) companies[d.yearMonth] = {};
答案 1 :(得分:0)
根据原始JSON中原始yearMonth属性的值创建一个Set。
重复此设置。在每次迭代中,过滤原始的JSON,并比较yearMonth属性。过滤后的数组将按yearMonth包含公司。我目前无法提供代码示例,但希望您能理解。