简体   繁体   中英

Reduce a Javascript Array of Objects using nested keys

I have the following array which contains a list of javascript objects. I am trying to use the reduce function to convert it into a single object with nested key groupings.

The array looks like the following:

 [ { "product": 1, "date": "2020-01-01", "price": 100 }, { "product": 2, "date": "2020-01-01", "price": 102 }, { "product": 1, "date": "2020-01-02", "price": 99 }, { "product": 2, "date": "2020-01-02", "price": 92 }, { "product": 1, "date": "2020-01-03", "price": 101 }, { "product": 2, "date": "2020-01-03", "price": 22 } ]

And this is the result which I am trying to achieve:

 { 1:{ "2020-01-01":{ "product": 1, "date": "2020-01-01", "price": 100 }, "2020-01-02":{ "product": 1, "date": "2020-01-02", "price": 99 }, "2020-01-03":{ "product": 1, "date": "2020-01-03", "price": 101 } }, 2:{ "2020-01-01":{ "product": 2, "date": "2020-01-01", "price": 102 }, "2020-01-02":{ "product": 2, "date": "2020-01-02", "price": 92 }, "2020-01-03":{ "product": 2, "date": "2020-01-03", "price": 22 } } }

I have tried the following but I only get a single date per product:

 pricelist.reduce((obj, item) => { obj[item['product']] = {}; obj[item['date']][item['product']] = item; return obj; }, {});

Please may you help me understand what I'm doing wrong?

By having only one product per date, you could take the direct target for assigning.

In your approach you changed product with date and this does not work.

 var pricelist = [{ product: 1, date: "2020-01-01", price: 100 }, { product: 2, date: "2020-01-01", price: 102 }, { product: 1, date: "2020-01-02", price: 99 }, { product: 2, date: "2020-01-02", price: 92 }, { product: 1, date: "2020-01-03", price: 101 }, { product: 2, date: "2020-01-03", price: 22 }], result = pricelist.reduce((obj, item) => { obj[item.product] = obj[item.product] || {}; obj[item.product][item.date] = item; return obj; }, {}); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM