代码之家  ›  专栏  ›  技术社区  ›  Wasteland

js-将对象合并到数组中

  •  0
  • Wasteland  · 技术社区  · 3 年前

    我有一个数组,其结构如下:

    const screens = [
      {
        name: 'John',
        options: {
          headerTitle: 'Book Title',
        },
      },
      {
        name: 'Bill',
        options: {
          headerTitle: 'Another title',
        },
      },
    ];
    

    const header = {
        headerStyle: {
          borderBottomWidth: 0.5,
          borderColor: 'black',
        },
    };
    

    header2 = [
      {
        borderColor: 'red',
        borderWidth: 0.5,
      },
    ];
    

    最终目标是:

    const screens = [
          {
            name: 'John',
            options: {
              headerTitle: 'Book Title',
              headerStyle: {
                borderColor: 'red',
                borderWidth: 0.5,
            },
          },
          {
            name: 'Bill',
            options: {
              headerTitle: 'Another title',
              headerStyle: {
                bordercolor: 'red',
                borderWidth: 0.5,
            },
          },
        ];
    

    我一直在谷歌搜索spread操作符,但似乎无法将两者合并。

    2 回复  |  直到 3 年前
        1
  •  2
  •   Phil    3 年前

    我们的想法是 map 将现有阵列转换为新阵列,并合并您的选项

    const screens = [{"name":"John","options":{"headerTitle":"Book Title"}},{"name":"Bill","options":{"headerTitle":"Another title"}}]
    
    const header = {
      headerStyle: {
        borderBottomWidth: 0.5,
        borderColor: 'black'
      }
    }
    
    const merged = screens.map(screen => ({
      ...screen,
      options: {
        ...screen.options,
        ...JSON.parse(JSON.stringify(header))
      }
    }))
    
    console.log(merged)
    .as-console-wrapper { max-height: 100% !important; }

    JSON.parse(JSON.stringify(header)) ,数组中的每个对象将共享相同的 headerStyle 对象引用。可能有更简单的方法可以使用扩展语法中断对象引用,但是考虑到要合并的对象的潜在动态特性,可以使用 JSON 方法是一种方便的通用方法。

        2
  •  1
  •   nay    3 年前

    如果这对你有帮助的话。
    只需循环数组并附加headerStyle。这三个点表示提取数据,以防止引用。

    const screens = [
      {
        name: 'John',
        options: {
          headerTitle: 'Book Title',
        },
      },
      {
        name: 'Bill',
        options: {
          headerTitle: 'Another title',
        },
      },
    ];
    
    const header = {
        headerStyle: {
          borderBottomWidth: 0.5,
          borderColor: 'black',
        },
    };
    
    screens.forEach(item=>{item.options['headerStyle']={...header.headerStyle}})
    
    console.log(screens)