首页 > 解决方案 > 如何按顺序对 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来做?感谢您的任何提示/建议。

标签: javascriptarraysobject

解决方案


正如@ggorlen 建议的那样,不能保证对象中键的顺序。您可以按照需要的顺序迭代orderedData以访问每个对象的键:

jData.map((item) => (
  <ul>
    orderedData.map((key) => <li>{key}: {item[key]}</li>)
  </ul>
));

推荐阅读