我正在尝试将我的输出转换为基于字符的格式化输出。
我目前设法在产品标题旁边输出每个类别。
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)
关于如何过滤我得到此输出的结果对象有什么建议吗?
感谢您的回复!
最佳答案
您需要先收集所有类别及其产品,然后呈现结果。
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; }
关于javascript - 格式化字符串的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50966636/