0

I've been really struggling with this piece of code.

I have an object that goes like:

var obj = {
    Name: 'Test',
    Id: 1,
    Address: 'addr'
}

And an array that goes like:

var arr = [1,0,2]; 

I want the properties of the object to be sorted with the indices given in the second one.

The result should then be something like:

var obj = {
    Id: 1,
    Name: 'Test',
    Address: 'addr'
}

I'm really looking forward to your replies.

12
  • 4
    Object properties have an ordering that is determined by the runtime. You should absolutely not write code that depends on property ordering, because your code will be subject to weird bugs. Instead, put the property names in an array (or get them with Object.keys()) and sort them according to your needs, and then access the object properties via that array. Commented May 11, 2021 at 20:36
  • Looks like an XY question. What do you mean by "properties of the object to be sorted after the indices"? Commented May 11, 2021 at 20:40
  • @Pointy Yeah I'm not sure about the sorting though. I will be using the resulting object to fill a .csv file. I'm aware that I can access the keys through Object.keys and then what? How can I use that array I showed to change the order and afterwards assign it back to the object? Commented May 11, 2021 at 20:40
  • @Phalgun Look at the result object. The properties should have the order of the given indices provided by the array. Commented May 11, 2021 at 20:41
  • 3
    @Neoyaru what you're asking for is not something objects are designed for. They're meant for unordered key/value pairs, not ordered data. The keys do technically have an order, but as pointy said, you should not write code that relies on it. If you'll tell us what you plan to do with your hypothetical ordered object, perhaps we can suggest an alternative way to get there. Commented May 11, 2021 at 20:51

1 Answer 1

1

You cannot reliably set the order of the properties in an object. You will need to rethink your approach to this problem so that the order is handled by an array, not an object. The array can then be used to write code that accesses properties in a specific order, even though the object doesn't actually have them in that order.

For example:

const columns = ['Id', 'Name', 'Address'];

const data = [{
  Name: 'Test',
  Id: 1,
  Address: 'addr'
}, {
  Address: 'addr2',
  Id: 1,
  Name: 'Test2',
}];

let csv = columns.join(',') + '\n';
data.forEach(obj => {
  const row = columns.map(propertyName => {
    return obj[propertyName];
  });
  csv = csv + row.join(',') + '\n'
})

console.log(csv);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.