Javascript 交换对象元素

Javascript swap object elements

如何通过索引(oldIndex,newIndex)交换数组中对象中的两个元素?

源数组:

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

我需要获取一个新的对象数组,oldIndex = 0,newIndex = 1

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

最好使用 ES6

const newData = data.map(item => ({
  sex: item.sex,
  city: item.city,
  car: item.car,
  name: item.name
});

我不知道你为什么要这样做,但这应该行得通。

这样做没有意义,因为对象属性的顺序在很大程度上取决于浏览器引擎。请参考这个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.

您可以参考此solution替代解决方案。