Friday 9 June 2017

JavaScript extract JSON data into a new object

I'm trying to extract multiple pieces of data out of a JSON file to put into an object, so that I can convert the object back to JSON with only the data I want.

I was thinking an object like this would be possible:

data = {
  0: {
    lat: xxxx,
    lng: xxxx,
    name: xxxx
  },
  1: {
    ...
  }
};

Here's the loop that extracts the data, but I can't figure out how to assign the three data points to the same object (data.0, data.1, ...) within the object (data).

for (let z = 0; z < data.features.length; z++) {
  finalData.z.lat = data.features[z].center[0];
  finalData.z.lng = data.features[z].center[1];
  finalData.z.name = data.features[z].text;
}

I don't mind if an array is used instead on an object as they can be JSON.stringified, too. The length of data.features varies depending on the API call.

I'm hoping to accomplish this using vanilla JS, but open to suggestions. It's being executed on the server (Node.js).



via MorganR

No comments:

Post a Comment