从数组数组创建对象数组,其中键取决于数组元素的数据类型

Creating an array of objects from an array of arrays where the key depends on both the data type of array element

我有一个数组数组 this.rowDataOfAllGrids,它导致多个数组的结构如下:

[
    [123,"Hello", 3455],
    [456, "Blue Falcon", 53],
    [20, "Yellow Apple", 134]
    .... (this could contain hundreds of arrays)
]

总而言之,数组中有 1 个项目是字符串,其余是值。

我正在尝试使用 this.rowDataOfAllGrids 创建一个对象,无论字符串在哪里(根据项目的顺序),它都分配给键类别,其余分配给键 series_1, series_2 取决于他们的顺序。所以基于上面的 this.rowDataOfAllGrids 这样的东西:

[{
    series_1: 123,
    category: "Hello"
    series_2: 3455
}
{
    series_1: 456,
    category: "Blue Falcon"
    series_2: 53
}
{
    series_1: 20,
    category: "Yellow Apple"
    series_2: 134
}]

这是我目前的情况:

    createObjectFromArray() {
      var gridRowDataLength = this.rowDataOfAllGrids.reduce((accumulator, value) => value.length, 0);

      for (var i = 1; i<=gridRowDataLength-1; i++) {
        let valueVariables = "series_" + (i);
        this.arrayOfValuesToUseAsKeys.push(valueVariables);
      }

      // this creates the object where we get the first value, assign it to category and assign the rest to series_# depending on the order.

      this.objectFromArray = this.rowDataOfAllGrids.map(
        ([category, ...rest]) => Object.fromEntries([
          ['category', category],
          ...rest.map((series, i) => ['series_' + (i+1), value])
        ])
      );
    },

如果数组的格式为 ["Yo", 2, 53 3455],则此方法有效,其中字符串项位于所有其他项的左侧。但是在上面的示例中它不起作用。 但是,它在字符串左侧有任何数字的情况下不起作用,因为我们正在获取第一项并将其分配给类别和其余系列_#。

每个项目的顺序都是正确的,根据他们的顺序分配了一个编号 series_1、series_2 等,但是我不确定如何更改它以说明如果字符串在数组中的其他地方。

我的下一步是根据数据类型从数组中提取字符串。然后再次连接它,使其位于开头。这是个好主意吗?如果不是,那什么是好的流程?

const data = [
  [123,"Hello", 3455],
  ["Blue Falcon", 456, 53],
  [20, 134, "Yellow Apple"]
];

const transform = arr => arr.map((e) => {
  let series = 1;

  return e.reduce((o, ee) => {
    if (typeof ee === 'string') {
      o.category = ee;
    } else {
      o[`series_${series++}`] = ee;
    }
    
    return o;
  }, {});
});

console.log(transform(data));

const gridData = [
  [123, "Hello", 3455],
  [456, "Blue Falcon", 53],
  [20, "Yellow Apple", 134]
]


const res = gridData.map(item => {
  let count = 1
  let temp = {}
  item.forEach(it => {
    if (typeof it === 'string') {
      temp.category = it
    } else {
      temp[`series_${count++}`] = it
    }
  })

  return temp;
})

console.log(res)

遍历行的元素,检查类型。如果是字符串,则赋给category属性,否则赋给下series_X属性.

const rowDataOfAllGrids = [
    ["Hello", 123,3455],
    [456, "Blue Falcon", 53],
    [20, 134, "Yellow Apple"]
];

let result = rowDataOfAllGrids.map(row => {
  let obj = {};
  let i = 1;
  row.forEach(el => {
    if (typeof el == "string") {
      obj.category = el;
    } else {
      obj["series_" + i++] = el;
    }
  });
  return obj;
});

console.log(result);