使用对象属性创建一个数组

Use an object attribute to create an array with it

大家好,我想做一些“简单”但不适合我的事情,我有这个数组

[
  { x: 'bmw', vehicule_type: car, y: 1 },
  { x: 'mercedes', vehicule_type: car, y: 2 },
  { x: 'airbus', vehicule_type: plane, y: 1 }
]

我想把它改造成这个东西

[
  car : [{ x: 'bmw',  y: 1 },  { x: 'mercedes', y: 1 }]
  plane: [{ x: 'airbus',  y: 1 }]
] 

我找不到方法,我看到我可以使用“reducer()”,但其余的我迷路了

我不确定这是否是最好的方法;可能不是,但这是我想出的..

let array = [{
    x: 'bmw',
    vehicle_type: "car",
    y: 1
  },
  {
    x: 'mercedes',
    vehicle_type: "car",
    y: 2
  },
  {
    x: 'airbus',
    vehicle_type: 'plane',
    y: 1
  },
  {
    x: 'mercedes',
    vehicle_type: "car",
    y: 2
  }
]

function sortByType(array) {
  const vehicles = {};
  for (let object of array) {
    let vehicle = {},
      type = undefined;
    for (let property in object) {
      if (type === undefined) type = object["vehicle_type"];
      if (vehicles[type] === undefined) vehicles[type] = [];
      if (property === "vehicle_type") continue;

      vehicle[property] = object[property];
    }
    vehicles[type].push(vehicle);
  }
  return vehicles
}

const vehicles = sortByType(array)
console.log(vehicles)

您可以使用 Array.prototype.reducevehicle_type 对数据进行分组。

const 
  data = [
    { x: "bmw", vehicle_type: "car", y: 1 },
    { x: "mercedes", vehicle_type: "car", y: 2 },
    { x: "airbus", vehicle_type: "plane", y: 1 },
  ],
  result = data.reduce(
    (r, { vehicle_type: t, ...o }) => ((r[t] ??= []).push(o), r),
    {}
  );

console.log(result);

如果您觉得难以理解上述解决方案,请参阅这个更具描述性的版本:

const 
  data = [
    { x: "bmw", vehicle_type: "car", y: 1 },
    { x: "mercedes", vehicle_type: "car", y: 2 },
    { x: "airbus", vehicle_type: "plane", y: 1 },
  ],
  result = data.reduce((r, { vehicle_type: t, ...o }) => {
    if (!r[t]) {
      r[t] = [];
    }
    r[t].push(o);
    return r;
  }, {});

console.log(result);

相关文档:

下面介绍的是实现所需 objective 的一种可能方法。

代码段

const myTransform = arr => (
  arr.reduce(
    (acc, {vehicule_type, ...rest}) => (
      (acc[vehicule_type] ??= []).push({...rest}),
      acc
    ),
    {}
  )
);

/* EXPLANATION of the code

// method to transform the array
const myTransform = arr => (
  arr.reduce(         // iterate using ".reduce()" with "acc" as accumulator
    // destructure the iterator to acces "vehicule_type"
    (acc, {vehicule_type, ...rest}) => (
      // if "acc" doesn't have "vehicule_type", set it as empty array
      // and then, push "rest" (ie, x, y, other props, if any) into the array
      (acc[vehicule_type] ??= []).push({...rest}),
      // implicit return of "acc"
      acc
    ),
    {}      // initialize "acc" as an empty object
  )
);

*/

const dataArr = [
  { x: 'bmw', vehicule_type: 'car', y: 1 },
  { x: 'mercedes', vehicule_type: 'car', y: 2 },
  { x: 'airbus', vehicule_type: 'plane', y: 1 }
];

console.log(myTransform(dataArr));
.as-console-wrapper { max-height: 100% !important; top: 0 }

说明

在上面的代码片段中添加了内联评论。

编辑

正如 Bergi 在下面的评论中指出的那样,使用 for 循环的替代方法也是可能的。这可能如下所示:

const myTransform = arr => {
  const res = {};
  for (const {vehicule_type, ...rest} of dataArr) {
    (res[vehicule_type] ??= []).push({...rest});
  };
  return res;
};

/* EXPLANATION
// alternative method to transform the array
const myTransform = arr => {
  // set up result "res" as an empty object "{}"
  const res = {};
  // iterate over elts of "dataArr"
  // destructure the iterator to directly access "vehicule_type"
  for (const {vehicule_type, ...rest} of dataArr) {
    // if "vehicule_type" not already in "res", 
    // then, set it with a value of empty array
    // push the remaining props "...rest" into the array
    (res[vehicule_type] ??= []).push({...rest});
  };
  // return the result
  return res;
};
*/

const dataArr = [
  { x: 'bmw', vehicule_type: 'car', y: 1 },
  { x: 'mercedes', vehicule_type: 'car', y: 2 },
  { x: 'airbus', vehicule_type: 'plane', y: 1 }
];

console.log(myTransform(dataArr));
.as-console-wrapper { max-height: 100% !important; top: 0 }

您可以使用Array.prototype.reduce() combined with Destructuring assignment

代码:

const data = [{ x: 'bmw', vehicle_type: 'car', y: 1 },{ x: 'mercedes', vehicle_type: 'car', y: 2 },{ x: 'airbus', vehicle_type: 'plane', y: 1 },]

const result = data.reduce(
  (a, { vehicle_type: v, ...c }) => ((a[v] = [...(a[v] || []), c]), a), 
  {}
)

console.log(result)