从 javascript 中的 reduce 获取分组结果的 属性

Get property of a grouped result from reduce in javascript

在分组结果中,我需要 vendor 的 属性 并存储在新数组中。但是给我一些错误。错误是 Error: words is not defined。 如何从分组列表中获取供应商 属性? 它即将获得结果并存储在新的 属性.

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

您的脚本中有一些无关的代码。

const result = words.filter(word => word.length > 6);

除了两行什么都不做的代码外,我认为您正在尝试获取每个组的供应商 ID - 在这种情况下,这只是底部代码中的 p哪个日志:

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

在第 36 行你写了 const result = words.filter(word => word.length > 6);words 没有在你的代码中的任何地方定义,这就是产生错误的原因。

关于你想达到什么目的,我不完全确定我理解了,但如果我理解了,你可以这样解决你的问题:

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 products = cart.products;

const vendors = products
  .map(product => product.vendor)
  .reduce((vendors, vendor) => {
    if (vendors.indexOf(vendor) < 0) {
      vendors.push(vendor);
    }
    return vendors;
  }, []);

const productsByVendor = products.reduce((dictionary, p) => {
  dictionary[p.vendor] = dictionary[p.vendor] || [];
  dictionary[p.vendor].push(p);
  return dictionary;
}, {});
console.log('Products grouped by vendor:\n', productsByVendor);

// in 'productsByVendor' the vendors are the keys of your object
console.log('Vendors:', Object.keys(productsByVendor));

/* if you want to retrieve the vendor of a specific product from 'productsByVendor'
 * Assumptions:
 * 1. cart.products[n].product is assumed to be a unique id (if that is not the case, you can use cart.products[n]._id instead)
 * 2. I am assuming that each product can be sold by only one vendor; if a product can be sold by more than one vendor you'll have to adjust a bit the function 
 */
getVendorIdFromGroupedProducts = (productId) => {
  for (let key of Object.keys(productsByVendor)) {
    for (let prod of productsByVendor[key]) {
      if (prod.product === productId) {
        return prod.vendor
      }
    }
  }
  return 'The product does not exist'
};
console.log('Vendor of product 1 is:', getVendorIdFromGroupedProducts(1));
console.log('Vendor of product 2 is:', getVendorIdFromGroupedProducts(2));
console.log('Vendor of product 3 is:', getVendorIdFromGroupedProducts(3));
console.log('Vendor of product 4 is:', getVendorIdFromGroupedProducts(4));

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); // useless line, you do not have variable 'words'
const f = cart.products.filter((p) => p.vendor == 1);
const products = cart.products; //better variable naming
var grouped = products.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]); //is array
}

要修复此代码 只需删除您使用变量 words 的行,因为您没有声明此类。

获取供应商值: grouped[p] 是一个数组。它没有 属性 vendor。但是你可以通过以下方式获得它:

for (const p in grouped) {
  console.log(grouped[p][0].vendor);
}

或获取它们的数组:

let vendors = Object.getOwnPropertyNames(grouped);

我想这会给你想要的结果:

let f = cart.products.map( p => p.vendor);
let newArray = f.filter((vendor,index,arr)=>vendor!==arr[index+1]);
newArray.forEach(element => {
    console.log(element);
});