3
\$\begingroup\$

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"
}
Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
asked May 26, 2021 at 20:26
\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

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);

answered May 28, 2021 at 3:43
\$\endgroup\$
0
4
\$\begingroup\$

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.

answered May 26, 2021 at 20:47
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.