I have an array of objects like this:
const jData = [
{
price: "500",
count: "10",
left: "150"
},
{
left: "75",
price: "350",
count: "40"
},
{
count: "200",
left: "50",
price: "7500"
}
];
and array of orderedData like this :
orderedData = ["price", "count", "left"]
I'm trying to sort my array of objects (jData) by keys so that keys will be in the same order as orderedData.
So far my code looks like this:
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>
);
}
I was able to get keys from my array of objects and sort them in the correct order, when I'm console logging keys
console.log(keys); => output is
["price"
1: "count"
2: "left"] // same order as in orderedData = ["price", "count", "left"]
but when I'm trying to sort my jData array so that keys in objects will be positioned in the same order, nothing changes.
let newData = jData.sort(
(a, b) =>
orderedData.indexOf(a) - orderedData.indexOf(b)
)
console.log(newData) => outputs objects with the same positioned keys.
What I would love to achieve is to display objects like this:
const jData = [
{
price: "500",
count: "10",
left: "150"
},
{
price: "350",
count: "40",
left: "75",
},
{
price: "7500"
count: "200",
left: "50",
}
];
I don't know if it's possible to do in Javascript? Thank you for any tip/suggestion.