2个关系数组,数据格式的转换

    var data = [
      {name: 'color', key: [1,2,3,4,5]},
      {name: 'size', key: [1,2,3,4,5]},
      {name: 'other', key: [1,2,3,4,5]},
      {name: 'type', key: [1,2,3,4,5]},
    ];
    var arr = [
      {
        color: "pink",
        size: "xm",
        other: 'aaa',
        type: 'one',
        price: 100,
        weight: 456
      },
      {
        color: "red",
        size: "xm",
        other: 'bbb',
        type: 'two',
        price: 789,
        weight: 789
      }
    ];
    

有两个数组 data 和 arr , 在data数组中的子对象的排列顺序为, 第一个: {name: 'color', key: [1,2,3,4,5]}, 第二个:{name: 'size', key: [1,2,3,4,5]}, 第三个:{name: 'other', key: [1,2,3,4,5]}, 第四个:{name: 'type', key: [1,2,3,4,5]}。
在arr 数组中, 子对象中 color: "pink" 和 color: "red", 属性,因为在data中, 属性name :"color", 排在data数组中的第一个, 所以arr数组中两个子对象的color: "pink" color: "red",要转换成 option1: "pink" 和 option1: "red",同样道理, 需要把arr 数组, 变成下面 arr1 的数据格式, 请问有什么比较灵活的方法可以实现?

    var arr1 = [
      {
        option1: "pink",
        option2: "xm",
        option3: "aaa",
        option4: "one",
        price: 100,
        weight: 456
      },
      {
        option1: "red",
        option2: "xm",
        option3: "bbb",
        option4: "two",
        price: 789,
        weight: 789
      }
    ]
阅读 1.4k
2 个回答

比较直接的方法,你也可以先将data转换成{ color: 'option1', size: 'option2' }这种

const transform = arr => {
  return arr.map(item => {
    let result = {};

    Object.keys(item).forEach(key => {
      const index = data.findIndex(d => d.name === key);

      if (index !== -1) {
        result[`option${index}`] = item[key];
      } else {
        result[key] = item[key];
      }
    });

    return result;
  });
};
const arr2=arr.map(item=>({
        option1:item[data[0].name],
        option2:item[data[1].name],
        option3:item[data[2].name],
        option4:item[data[3].name],
        price: item.price,
        weight: item.weight
    }))
    console.log(arr2)

属性不定:

const arr2 = arr.map(item => {
    const obj = {
        price: item.price,
        weight: item.weight
    };
    data.forEach((v, i) => {
        obj['option' + (i + 1)] = item[data[i].name]
    })
    return obj
})
console.log(arr2)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题