【问题标题】:Replace a "Tag" ( string ) with all the matches in JavaScript用 JavaScript 中的所有匹配项替换“标签”(字符串)
【发布时间】:2020-01-27 04:04:39
【问题描述】:

我正在尝试将如下所示的字符串置换为其可能的值。

我有一个格式如下的对象

{
  descriptions: ["Here's some <tag> exemple", "Can be something without Tag"],
  headlines: ["<tag> another exemple", "<tag>"]
}

我有一个具有不同排列的数组

["First","Second","Third"]

我正在尝试创建与排列一样多的对象以在最后得到这个结果

[
  {
    descriptions: ["Here's some First exemple", "Can be something without Tag"],
    headlines: ["First another exemple", "First"]
  },
  {
    descriptions: [
      "Here's some Second exemple",
      "Can be something without Tag"
    ],
    headlines: ["Second another exemple", "Second"]
  },
  {
    descriptions: ["Here's some Third exemple", "Can be something without Tag"],
    headlines: ["Third another exemple", "Third"]
  }
];

我被困在这里..

function foo(adCopy: AdCopy[], tag: string, variants: string[]) {
  variants.forEach(variant => {
    adCopy.forEach(adCopy => {
      adCopy.headlines.map(headline => {

      })
    })
  })
}

【问题讨论】:

    标签: javascript reactjs typescript logic frontend


    【解决方案1】:
    const mapObj = (obj, map) => Object.fromEntries(Object.entries(obj).map(map));
    
    const result = variants.map(variant =>
       adCopies.map(adCopy =>
         mapObj(adCopy, ([key, values]) => ([
            key, 
            values.map(value => value.replace(/<tag>/, variant))
         ]))
       )
    );
    

    您可以将所有变量映射到它们的排列,并且您可以使用Object.fromEntriesObject.entries 来映射对象。

    【讨论】:

      【解决方案2】:

      假设您不想修改原始对象,您可以这样做:

      let obj = {
      	descriptions: ["Here's some <tag> exemple", "Can be something without Tag"],
      	headlines: ["<tag> another exemple", "<tag>"]
      };
      let permutations = ['First', 'Second', 'Third'];
      
      let objMapped = permutations.map(permutation =>
      	Object.entries(obj).reduce((acc, [key, values]) => {
      		acc[key] = values.map(value => value.replace(/<tag>/g, permutation));
      		return acc;
      	}, {}));
      
      console.log(objMapped);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-29
        • 2020-06-23
        • 2022-11-19
        • 1970-01-01
        • 2016-09-26
        • 1970-01-01
        • 1970-01-01
        • 2019-06-16
        相关资源
        最近更新 更多