Search code examples
javascriptreducefor-in-loop

Get property of a grouped result from reduce in javascript


In grouped result I need the property of vendor and store in new array. but the give me some error. the error is Error: words is not defined. how can I get vendor property from grouped list? it is about to get result and store in new property.

const cart = {
    "_id": 2,
    "owner": 7,
    "products": [{
        "_id": {
            "$oid": "5f06f9a4b8b878050fbc54b2"
        },
        "product": 1,
        "vendor": 1,
        "quantity": 2
    }, {
        "_id": {
            "$oid": "5f06f9a4b8b878050fbc54b3"
        },
        "product": 2,
        "vendor": 1,
        "quantity": 1
    }, {
        "_id": {
            "$oid": "5f06f9a4b8b878050fbc54b4"
        },
        "product": 4,
        "vendor": 2,
        "quantity": 1
    }],
    "createdAt": {
        "$date": "2020-06-21T06:46:40.111Z"
    },
    "updatedAt": {
        "$date": "2020-07-09T11:04:04.459Z"
    },
    "__v": 0,
    "totalPrice": 265
}

const product = cart.products;
var grouped = product.reduce((dictionary, p) => {
  dictionary[p.vendor] = dictionary[p.vendor] || [];
  dictionary[p.vendor].push(p);
  return dictionary;
}, {})
for (const p in grouped) {
  console.log(grouped[p].vendor)
}


Solution

  • Aside from the 2 lines of code which do nothing, I think you're trying to get the id of the vendor for each group - in which case this is just p in your code at the bottom which logs:

    const cart = {"_id":2,"owner":7,"products":[{"_id":{"$oid":"5f06f9a4b8b878050fbc54b2"},"product":1,"vendor":1,"quantity":2},{"_id":{"$oid":"5f06f9a4b8b878050fbc54b3"},"product":2,"vendor":1,"quantity":1},{"_id":{"$oid":"5f06f9a4b8b878050fbc54b4"},"product":4,"vendor":2,"quantity":1}],"createdAt":{"$date":"2020-06-21T06:46:40.111Z"},"updatedAt":{"$date":"2020-07-09T11:04:04.459Z"},"__v":0,"totalPrice":265}
    
    //const result = words.filter(word => word.length > 6);
    //const f = cart.products.filter(p => p.vendor == 1);
    const product = cart.products;
    var grouped = product.reduce((dictionary, p) => {
      dictionary[p.vendor] = dictionary[p.vendor] || [];
      dictionary[p.vendor].push(p);
      return dictionary;
    }, {})
    let vendor;
    for (const p in grouped) {
      console.log("vendor=", p, " count of items=", grouped[p].length)
    }