-2

how to swap two elements in an object in the array by index (oldIndex, newIndex)?

source array:

const data = [
  {
    city: 'London',
    sex: 'Female',
    car: 'Honda Accord',
    name: 'Lisa',
  },
  ...
];

I need to get a new array of objects with oldIndex = 0, newIndex = 1

const newData = [
  {
    sex: 'Female',
    city: 'London',
    car: 'Honda Accord',
    name: 'Lisa',
  },
  ...
];

preferably using ES6

user2005679
  • 186
  • 1
  • 2
  • 7

2 Answers2

2

There is no point in doing that as the ordering of object properties are very much depending on the browser engines. Please refer to this material.

Note: As contrasted with iterating over an array's indices in a numerically ordered way (for loop or other iterators), the order of iteration over an object's properties is not guaranteed and may vary between different JS engines. Do not rely on any observed ordering for anything that requires consistency among environments, as any observed agreement is unreliable.

You can refer to this solution for alternative solution.

Isaac
  • 12,042
  • 16
  • 52
  • 116
0
const newData = data.map(item => ({
  sex: item.sex,
  city: item.city,
  car: item.car,
  name: item.name
});

I have no idea why you want to do this, but that should work.

ajthyng
  • 1,245
  • 1
  • 12
  • 18