问答

js 二维数组解析新结构

作者:admin 2021-06-15 我要评论

由二维数组规格,得到一个新的result结果,要怎么写 const rule = [ ["白色", "绿色", "黄色"], ["三层", "四层"]]const result = [ { 'index_0_0': '白色', 'in...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

由二维数组规格,得到一个新的result结果,要怎么写

const rule = [
    ["白色", "绿色", "黄色"],
    ["三层", "四层"]
]

const result = [
    { 'index_0_0': '白色', 'index_1_0': '三层', },
    { 'index_0_1': '绿色', 'index_1_0': '三层', },
    { 'index_0_2': '黄色', 'index_1_0': '三层', },
    { 'index_0_0': '白色', 'index_1_1': '四层', },
    { 'index_0_1': '绿色', 'index_1_1': '四层', },
    { 'index_0_2': '黄色', 'index_1_1': '四层', },
]
###

这个就是全组合,想明白思路其实就不复杂。
就想一个物品,最开始仅仅是一个物品,但是后来知道它有颜色,就会有3个不同的物品;然后又有2种层数,就分别匹配到3种颜色上,就是6个不同物品。

可以用一个对象{}表示一个物品,里面没有任何特征,就是最初始的物品,然后循环每种特征,将每种特征的每一个值与当前结果组合得到新的结果,遍历完所有特征得到所有物品组合。

写个比较通用的,即便除了颜色、层数还有其它特征,都可以使用这个函数得到结果:

function getResult(list) {
    let result = [{}] // 初始一个物品,没啥特征 
    for (let i = 0; i < list.length; i++) { // 循环每类特征
      let newResult = []
      for (let j = 0; j < list[i].length; j++) { // 循环一类特征的所有值
        result.forEach(item => {
          newResult.push({
            ...item,
            [`index_${i}_${j}`]: list[i][j]
          })
        })
      }
      result = newResult
    }
    return result
}

测试:
image.png

###

emm 首先你这个数据源是不规范的 ... 建议让后端给
{ color, floor } 这种样式的,

const color = rule[0];
const floor = rule[1];
const color_len = color.length;
const floor_len = floor.length;
let result = new Array(color_len * floor_len).fill({});

result.map((item, index) => {
    const key0 = index % color_len;
    const key1 = Math.floor(index / color_len);
    let temp = {};

    temp[`index_0_` + key0] = floor[key0];
    temp[`index_1_` + key1] = floor[key1];
    return temp
})
###
const rule = [
  ["白色", "绿色", "黄色"],
  ["三层", "四层"],
];

const result = [
  { index_0_0: "白色", index_1_0: "三层" },
  { index_0_1: "绿色", index_1_0: "三层" },
  { index_0_2: "黄色", index_1_0: "三层" },
  { index_0_0: "白色", index_1_1: "四层" },
  { index_0_1: "绿色", index_1_1: "四层" },
  { index_0_2: "黄色", index_1_1: "四层" },
];

const [colors, layers] = rule;

const r = layers.map((color, index) => {
  return colors.map((layer, i) => {
    return {
     [`index_0_${i}`]: layer,
     [`index_1_${index}`]: color
    }
  });
}).flat();


console.log(r)

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • js 二维数组解析新结构

    js 二维数组解析新结构

  • docker 端口映射的宿主机端口被内部感

    docker 端口映射的宿主机端口被内部感

  • js操作原生

    js操作原生

  • spring boot 运行中动态切换rabbitmq连

    spring boot 运行中动态切换rabbitmq连

腾讯云代理商
海外云服务器