我正在尝试将输出转换为基于字符的格式化输出。
我目前设法在产品标题旁边输出每个类别。
let result = {
"2": {
"title": "Product 1",
"category": [{
"cat_name": "Category 1",
}],
"price": "99"
},
"3": {
"title": "Product 2",
"category": [{
"cat_name": "Category 2",
}],
"price": "22"
},
"4": {
"title": "Product 3",
"category": [{
"cat_name": "Category 1",
}],
"price": "55"
}
}
let items = ""
for (var key in result) {
items += `*${result[key].category["0"].cat_name}:* ->${result[key].title} ($${result[key].price})` + "\n"
}
console.log(items)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
但是,作为输出,我希望拥有:
*Category 1:*
->Product 1 ($99)
->Product 3 ($55)
*Category 2:*
->Product 2 ($22)
任何建议如何过滤我得到此输出的结果对象?
感谢您的答复!
答案 0 :(得分:1)
您需要首先收集所有类别及其产品,然后呈现结果。
var data = { 2: { title: "Product 1", category: [{ cat_name: "Category 1" }], price: "99" }, 3: { title: "Product 2", category: [{ cat_name: "Category 2" }], price: "22" }, 4: { title: "Product 3", category: [{ cat_name: "Category 1" }], price: "55" } },
categories = Object.create(null);
Object.values(data).forEach(({ title, category, price }) =>
category.forEach(({ cat_name }) =>
(categories[cat_name] = categories[cat_name] || []).push({ title, price, cat_name })));
Object.entries(categories).forEach(([category, products]) => {
console.log(`*${category}*:`);
products.forEach(({ title, price }) => console.log(`->${title} ($${price})`));
});
console.log(categories);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
执行此操作的常见方法是为类别构建对象,然后将每个产品添加到相关类别中。我在以下代码段中完成了此操作。
就像@NinaScholz的回答一样,您可以使函数更短,但我决定这样保留它们,以便更清楚地了解发生了什么。
let result = {
"2": {
"title": "Product 1",
"category": [{
"cat_name": "Category 1",
}],
"price": "99"
},
"3": {
"title": "Product 2",
"category": [{
"cat_name": "Category 2",
}],
"price": "22"
},
"4": {
"title": "Product 3",
"category": [{
"cat_name": "Category 1",
}],
"price": "55"
}
}
const categories = {}
Object.keys(result).forEach((key) => {
const item = result[key]
const itemCategories = item.category
itemCategories.forEach((category) => {
if (!(category.cat_name in categories)) {
categories[category.cat_name] = []
}
categories[category.cat_name].push({
title: item.title,
price: item.price
})
})
})
Object.keys(categories).forEach((category) => {
console.log('*' + category + ':*')
const items = categories[category]
items.forEach((item) => {
console.log('->' + item.title + ' ($' + item.price + ')')
})
})