The following code is working as expected but I'm wondering if there's a way to use Object.assign
, or some other approach, to build the derivedData
object so that it doesn't need to be initialized as an empty object and then populated in a subsequent step.
const data = [
{"period": "2021年05月01日", "quantity": "28"},
{"period": "2021年06月01日", "quantity": "42"},
{"period": "2021年07月01日", "quantity": "66"}
];
const derivedData = {};
data.forEach(o => {
derivedData[o.period] = o.quantity
});
console.log(data);
console.log(derivedData);
Expected output of derivedData
:
{
"2021年05月01日": "28",
"2021年06月01日": "42",
"2021年07月01日": "66"
}
2 Answers 2
This can be achieved by using the handy Object.fromEntries() function. It takes a list of key-value pairs and constructs an object from the list. For example:
> Object.fromEntries([['a', 1], ['b', 2]])
{ a: 1, b: 2 }
In your scenario, we can construct these key-value pairs by simply doing using array.map() on your data. This is what a complete solution looks like:
const data = [
{"period": "2021-05-01", "quantity": "28"},
{"period": "2021-06-01", "quantity": "42"},
{"period": "2021-07-01", "quantity": "66"}
];
const derivedData = Object.fromEntries(
data.map(({ period, quantity }) => [period, quantity])
);
console.log(data);
console.log(derivedData);
While it technically still would initialize it as an empty object, one could build derivedData
with one call to Array.prototype.reduce()
. It is similar to forEach()
except that the first argument of the callback function is an accumulator variable, that needs to be returned at the end of the function. See the snippet below for a demonstration.
const data = [
{"period": "2021-05-01", "quantity": "28"},
{"period": "2021-06-01", "quantity": "42"},
{"period": "2021-07-01", "quantity": "66"}
];
const derivedData = data.reduce((accumulator, o) => {
accumulator[o.period] = o.quantity;
return accumulator;
}, {});
console.log('derivedData: ', derivedData);
You may find these functional exercises interesting.
Good job using const
for variables that don't need to be re-assigned, and using common spacing conventions for modern JavaScript.