Reputation: 432
I have the following json file structure that includes years from 2008 to 2020, along with other keys such as location, name, etc.:
{"2008": 50, "2009": 60, "2010": 70, "2011": 80, etc...}
I am trying to group the years into another key and adding it to the original array:
{metric:
[{"year": 2008, "perc": 50},
{"year": 2009, "perc": 60},
{"year": 2010, "perc": 70},
{"year": 2011, "perc": 80}],
"2008": 50,
"2009": 60,
"2010": 70,
"2011": 80,
etc...
}
I think I need to create a range between 2008 to 2020, and if I detect a key that's within that range, I add to the metrics
group and add that to the array?
Upvotes: 0
Views: 161
Reputation: 522
you need to loop though the object and create a new one
const group => obj {
// create init object
let output = {
metric: []
}
// start loop
for (const key in obj) {
// check if object contains property
if (Object.hasOwnProperty.call(obj, key)) {
// check if key matches range and assign to metric if not
if (!(/20(0[8-9]|1[0-9]|20)/gm).test(key)) output.metric.push({
'year': key,
'perc': obj[key]
});
//assign value if matches between 2008 to 2020
else output[key] = obj[key]
}
}
// return new object
return output;
}
Upvotes: 0
Reputation: 1074929
What you have is an object, not an array. You can use a for-in
loop or a for-of
loop on Object.entries
or similar to loop through the object, and then it's a matter of converting the year to a number and comparing it to your range and if it's in range, adding it to the metric
array:
const data = {"2008": 50, "2009": 60, "2010": 70, "2011": 80, "2001": 20, "2002:": 30};
// Loop through the object
for (const [year, perc] of Object.entries(data)) {
// Get the year as a number
const yearValue = +year; // See note below
if (yearValue >= 2008 && yearValue <= 2020) {
// It's in range, get or create the `metric` array
const metric = data.metric ?? (data.metric = []);
// Add to it
metric.push({year, perc});
}
}
console.log(data);
(I added a couple of out-of-range years there to show the range working.)
Using unary +
to convert to number is just one of your options, I go through the full range of them in my answer here.
Upvotes: 2