Convert one object into another one

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.

Is the data always [2004, 2014, 2004, 2014, 2004, 2014 etc etc]? This is kinda important w/r/t how you approach this

1 Like

Yes, the data will always look like that.

I added some code trying to combine 2 objects at a time from the resulting array:

for (let index = 0; index < updatedData.length; index += 2) {

    const currElement = updatedData[index];

    console.log(currElement);

    const nextElement = updatedData[index + 1];

    console.log(nextElement);

    const combinedElement = { ...currElement, ...nextElement };

    console.log(combinedElement);

  }

But that is giving me:

{District: "Awaran", First: "57", Last: ""}
{District: "Awaran", First: "", Last: "57"}
{District: "Awaran", First: "", Last: "57"}
.
.
.
d3.csv("/data/Data4Pakistan-BalochistanOnly.csv").then(function(data) {
  console.log(data);

  let updatedData = [];
  for (let i = 0; i < data.length; i += 2) {
    let updatedObj = { District: "", First: "", Last: "" };
    updatedObj.District = data[i].District;
    updatedObj.First = data[i]["Poverty Rate (%)"]);
    updatedObj.Last = data[i+1]["Poverty Rate (%)"]);
    updatedData.push(updatedObj);
  });
  console.log(updatedData)
  return updatedData;
});

There is an issue with this: if there is an odd number of entries, it will blow up, so there needs to be careful error handling to avoid that. And if the data is ever not in 2004/2014 pairs, you’ll have an issue (so again, probably needs some sanity checks in there to ensure that the incoming data isn’t borked)

1 Like