我有两个数组如下:
var product1 = [
{
"Brand": "One Plus"
},
{
"Brand": "One Plus"
}
];
var product2 = [
{
"Brand": "One Plus"
},
{
"Brand": "Apple"
}
];
Run Code Online (Sandbox Code Playgroud)
我想遍历数组并打印以下内容:
you have 2 One Plusyou 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 输出,但如何以句子格式获得它?
这个怎么样?
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)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |