Reputation: 659
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).
Upvotes: 2
Views: 327
Reputation: 55740
Use []
notation which allows property access instead of dot
notation.
var dataArray = [];
for (let z = 0; z < data.features.length; z++) {
var finalData = {};
finalData[z] = {};
finalData[z].lat = data.features[z].center[0];
finalData[z].lng = data.features[z].center[1];
finalData[z].name = data.features[z].text;
dataArray.push(finalData);
}
if you are using ES6, then you can use []
pattern matching to get the computed property names.
let dataArray = [];
for (let z = 0; z < data.features.length; z++) {
let feature = data.features[z];
let structuredData = {
[z]: {
lat: feature.center[0],
lng: feature.center[1],
name: feature.text
}
};
dataArray.push(structuredData);
}
Upvotes: 1