我想使用这个库markdown-table从我的对象中生成一个表。前置要求是创建一个具有一定结构的数组。
在下面找到我的最小可行示例:
const obj = {
"2": {
"title": "Product 1",
"category": [{
"cat_name": "Graphic Card"
}],
"currency": "$",
"price": "513.40"
},
"3": {
"title": "Product 2",
"category": [{
"cat_name": "Graphic Card"
}],
"currency": "$",
"price": "599.00",
},
"4": {
"title": "Memory Ram 1",
"category": [{
"cat_name": "Memory"
}],
"currency": "$",
"price": "25.99",
},
"5": {
"title": "Product 3",
"category": [{
"cat_name": "Graphic Card"
}],
"currency": "$",
"price": "688.88",
},
"6": {
"title": "Adapter 1",
"category": [{
"cat_name": "PCI-E"
}],
"currency": "$",
"price": "48.99",
}
}
var result = Object.keys(obj).map(function(key) {
return [Number(key), obj[key]];
});
console.log(result)
<script src="https://raw.githubusercontent.com/wooorm/markdown-table/master/index.js"></script>
我的表得到以下结果:
| 2 | [object Object] |
| --- | --------------- |
| 3 | [object Object] |
| 4 | [object Object] |
| 5 | [object Object] |
| 6 | [object Object] |
但是,我尝试获取的结果数组应如下所示:
[
['Category', 'Model', 'Price'],
['Graphic Card', 'Prod 1', '$513.40'],
['Graphic Card', 'Product 2', '$599.00'],
['Graphic Card', 'Product 3', '$688.88'],
['Memory', 'Memory Ram 1', '$25.99'],
['PCI-E', 'Adapter 1', '$48.99']
]
对于为什么我的数组未正确解析并显示 [object Object]
有什么建议吗?
感谢您的回复!
最佳答案
[object Object]
在对象上调用 .toString() 时得到的结果。
看起来您需要显式传递您想要显示的值,因为它所做的就是在您传入的内容上调用 .toString() 。我不知道它将在哪里派生标题和值你。
像这样的事情可能会起作用:
let result = Object.keys(obj)
.reduce((result, key) => {
result.push([obj[key].category[0].cat_name, obj[key].title, obj[key].currency + obj[key].price]);
return result;
},
[['Category', 'Model', 'Price']]
);
这里发生的事情是我将 header 作为 .reduce() 中累加器的初始值传递,并且每次迭代都将一行值推送到累积数组上。
如果您想对结果进行排序:
let result = Object.keys(obj)
.sort((a, b) => {
if (obj[a].category[0].cat_name < obj[b].category[0].cat_name)
return -1;
if (obj[a].category[0].cat_name > obj[b].category[0].cat_name)
return 1;
if (obj[a].model < obj[b].model)
return -1;
if (obj[a].model > obj[b].model)
return 1;
return 0;
})
.reduce(...
这是一个 fiddle :https://jsfiddle.net/jmbldwn/t8Lvw2bj/2/
关于javascript - 将聚集的 obj 转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53133679/