I need to convert an array of objects.
This is what the incoming array looks like:
[
{District: "Awaran", Year: "2004", Poverty Rate (%): "57"},
{District: "Awaran", Year: "2014", Poverty Rate (%): "57"},
.
.
.
]
This is what I need it to look like after data manipulation:
[
{District: "Awaran", "First": 57, "Last": 57},
.
.
.
]
This is what my code looks like right now:
d3.csv("/data/Data4Pakistan-BalochistanOnly.csv").then(function(data) {
console.log(data);
let updatedData = [];
data.forEach(function(d) {
let updatedObj = { District: "", First: "", Last: "" };
updatedObj.District = d.District;
d["Year"] === "2004" ? (updatedObj.First = d["Poverty Rate (%)"]) : null;
d["Year"] === "2014" ? (updatedObj.Last = d["Poverty Rate (%)"]) : null;
updatedData.push(updatedObj);
});
console.log(updatedData);
});
And is resulting in this (incorrect) array:
[
{District: "Awaran", First: "57", Last: ""},
{District: "Awaran", First: "", Last: "57"}
.
.
.
]
The problem, I can see, is that the code has moved on to the next element of the array before the code checks if year is 2014. So it is building a new object by that point.
So I guess the question is: how can I build one object from 2 separate objects?
Each district will have 2 objects coming in, I want each district to have 1 object going out.