从对象数组创建一个字符串

use*_*094 3 javascript

我有两个数组如下:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];
Run Code Online (Sandbox Code Playgroud)

我想遍历数组并打印以下内容:

  1. 如果产品 1,输出 you have 2 One Plus
  2. 如果产品 2,输出 you have 1 One Plus and 1 Apple

下面是我试过的代码。

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);
Run Code Online (Sandbox Code Playgroud)

我能够获得 JSON 输出,但如何以句子格式获得它?

gyo*_*hza 5

这个怎么样?

var product1 = [{
    "Brand": "One Plus"
  },
  {
    "Brand": "One Plus"
  }
];
var product2 = [{
    "Brand": "One Plus"
  },
  {
    "Brand": "Apple"
  }
];

function countProducts(arr) {
  let counter = arr.reduce((acc, val) =>
    (acc[val.Brand] = (acc[val.Brand] || 0) + 1, acc), {});
  let strings = Object.keys(counter).map(k => `${counter[k]} ${k}`);
  return `You have ${strings.join(' and ')}`;
}

console.log(countProducts(product1));

console.log(countProducts(product2));
Run Code Online (Sandbox Code Playgroud)