【问题标题】:Combine object and arrays结合对象和数组
【发布时间】:2023-03-19 11:09:01
【问题描述】:

我正在尝试编写一个函数,该函数接受一个对象数组和无限数量的数组,并将它们组合成一个对象。输入将遵循以下模式:

let x = [{ name: 'Tom' }, { name: 'John' }, { name: 'Harry' }];
let y = [[1, 2, 3], 'id'];
let z = [['a', 'b', 'c'], 'value'];

combine(x, y, z);

yz 的第二个元素作为对象键。使用这些参数,函数应该返回以下数组:

[
  {
    name: 'Tom',
    id: 1,
    value: 'a'
  },
  {
    name: 'John',
    id: 2,
    value: 'b'
  },
  {
    name: 'Harry',
    id: 3,
    value: 'c'
  },
]

应该使用当前对象的索引来获取数组中的正确元素。我已经尝试解决这个问题:

function combine(object, ...arrays) {
  return object.map((obj, index) => {
    let items = arrays.map(arr => ({ 
      [arr[1]]: arr[0][index] 
    }));

    return Object.assign({}, obj, { items });
  });
}

这几乎可以完成这项工作,但导致数组项隐藏在嵌套的 items 数组中,我该如何解决这个问题?

【问题讨论】:

  • 使用map检查Demo

标签: javascript arrays object ecmascript-6


【解决方案1】:

您一直在分配 object 的对象,结果是一个新的对象,其中包含元素项(对象字面量的另一个特性)。

这种方法使用reduce代替map,直接赋值代替对象字面量。

function combine(object, ...arrays) {
  return object.map((obj, index) => {
    const items = arrays.reduce((acc, arr) => { 
      acc[arr[1]] = arr[0][index] ;
      return acc;
    }, {});

    return Object.assign({}, obj, items);
  });
}

const x = [{ name: 'Tom' }, { name: 'John' }, { name: 'Harry' }];
const y = [[1, 2, 3], 'id'];
const z = [['a', 'b', 'c'], 'value'];

combine(x, y, z);

您还可以在 Object.assign 中使用扩展运算符,如下所示:

function combine(object, ...arrays) {
  return object.map((obj, index) => {
    let items = arrays.map(arr => ({ 
      [arr[1]]: arr[0][index] 
    }));

    return Object.assign({}, obj, ...items);
  });
}

【讨论】:

    【解决方案2】:

    这几乎可以完成这项工作,但会导致数组项隐藏在嵌套项数组中

    问题在于items 是一个数组,而您只需要该特定map 回调中的当前项。此处无需嵌套循环。

    另外,我建议避免在每个 combine 调用中使用多个属性。生成的代码如下所示:

    function combine(objects, [values, key]) {
        return objects.map((o, i) =>
            Object.assign({[key]: values[i]}, o)
        );
    }
    combine(combine(x, y), z);
    

    如果你有多个扩展要做,你也可以使用

    [y, z].reduce(combine, x)
    

    【讨论】:

      【解决方案3】:

      使用地图和计算键,您可以实现这一点。 这是一个工作示例:

      let x = [{
          name: 'Tom'
      }, {
          name: 'John'
      }, {
          name: 'Harry'
      }];
      let y = [[1, 2, 3], 'id'];
      let z = [['a', 'b', 'c'], 'value'];
      
      let result = [];
      
      x.map(function (el, index) {
        result.push(el);
        let index = result.length -1;
      
        result[index][y[1]] = y[0][index];
        result[index][z[1]] = z[0][index];
      });
      
      console.log(result);
      

      【讨论】:

        猜你喜欢
        • 2019-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-12
        相关资源
        最近更新 更多