I'm trying to sort an array of objects by a key in a particular position. The only problem is that each object has a different key name.
here is an example of an object i'm trying to sort:
let data = [
{name: "James", x: 3, },
{name: "Thomas", y: 1},
{name: "Zack", z: 2}
];
I'm trying to sort it by the 2nd key so the order should be
[
{name: "James", x: 3, },
{name: "Zack", z: 2},
{name: "Thomas", y: 1}
];
here is how I'm trying to do it:
let data = [
{name: "James", x: 3, },
{name: "Thomas", y: 1},
{name: "Zack", z: 2}
];
data.sort((a, b) => {
let key1 = Object.keys(a)[1];
let key2 = Object.keys(b)[1];
return a[key1] > b[key2]
});
console.log(data)
Here is my jsbin
https://jsbin.com/lihefodoni/edit?html,js,console
Not sure why it's not working. I'm trying to do this in my react Application so I don't know if there's something different I need to do?
Object.keys()documentation says: "in the same order as we get with a normal loop.". Moving on to thefor...indocumentation: "Afor...inloop iterates over the properties of an object in an arbitrary order (see thedeleteoperator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting)."