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" } 
\$\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);

    \$\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.

      \$\endgroup\$

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.