javascript - 如何按顺序对 Javascript 中的对象数组进行排序?
问题描述
我有一个这样的对象数组:
const jData = [
{
price: "500",
count: "10",
left: "150"
},
{
left: "75",
price: "350",
count: "40"
},
{
count: "200",
left: "50",
price: "7500"
}
];
和这样的orderedData数组:
orderedData = ["price", "count", "left"]
我正在尝试按键对对象数组(jData)进行排序,以便键与orderedData 的顺序相同。
到目前为止,我的代码如下所示:
import "./styles.css";
export default function App() {
const jData = [
{
price: "500",
count: "10",
left: "150"
},
{
left: "75",
price: "350",
count: "40"
},
{
count: "200",
left: "50",
price: "7500"
}
];
const orderedData = ["price", "count", "left"];
let res = jData?.flatMap((x) => Object.keys(x));
var unique = res.filter(function (elem, index, self) {
return index === self.indexOf(elem);
});
const keys = unique?.filter((key) => orderedData.includes(key));
console.log(keys)
let newData = jData.sort(
(a, b) =>
orderedData.indexOf(a) - orderedData.indexOf(b)
)
console.log(newData)
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
当我在控制台记录键时,我能够从我的对象数组中获取键并以正确的顺序对它们进行排序
console.log(keys); => output is
["price"
1: "count"
2: "left"] // same order as in orderedData = ["price", "count", "left"]
但是当我试图对我的 jData 数组进行排序以便对象中的键以相同的顺序定位时,没有任何变化。
let newData = jData.sort(
(a, b) =>
orderedData.indexOf(a) - orderedData.indexOf(b)
)
console.log(newData) => outputs objects with the same positioned keys.
我想要实现的是显示这样的对象:
const jData = [
{
price: "500",
count: "10",
left: "150"
},
{
price: "350",
count: "40",
left: "75",
},
{
price: "7500"
count: "200",
left: "50",
}
];
我不知道是否可以用Javascript来做?感谢您的任何提示/建议。
解决方案
正如@ggorlen 建议的那样,不能保证对象中键的顺序。您可以按照需要的顺序迭代orderedData
以访问每个对象的键:
jData.map((item) => (
<ul>
orderedData.map((key) => <li>{key}: {item[key]}</li>)
</ul>
));
推荐阅读
- javascript - 允许电子 `requires` 在 Vite 中原封不动地通过
- r - 基于公共 id 绑定行
- grafana - Grafana 图形条不均匀
- git - 没有可写文件系统的 Git 提交元数据?
- wordpress - 我想将我的 woocommerce 网站重定向到我的域的子目录
- ios - theos 编译缺少的 sdk 框架头文件
- python - 如何将相应的 HTML 结尾附加到每条抓取的文本?
- php - 如何在 PHP Laravel 中隐藏 URL 值
- node.js - 如何使用 Axios + 文本字段数据发送文件
- reactjs - 开玩笑嘲笑 MobX 商店在测试之间没有重置