用JavaScript中的所有匹配项替换“标记”(字符串)

时间:2019-09-26 20:21:10

标签: javascript reactjs typescript logic frontend

我试图置换一个字符串,其可能的值如下。

我有一个具有以下格式的对象

{
  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 => {

      })
    })
  })
}

2 个答案:

答案 0 :(得分:1)

Matrix([[Poly(x**2 + 1, x, domain='ZZ')]])

您可以映射所有变量到它们的排列,并且可以使用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.fromEntries来映射对象。

答案 1 :(得分:0)

假设您不想修改原始对象,可以执行以下操作:

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);