javascript 通过使用正则表达式搜索字段和值来创建对象

问题描述 投票:0回答:1

我希望你能帮我解决这个问题。我需要在文本中搜索字段和值并将它们转换为对象。

文字示例

<@if VERSION = "A1">

<@assign CTA = "blue">
<@assign CTA2 = "green">

<@elseif VERSION = "A2">

<@assign CTA = "red">
<@assign CTA2 = "yellow">

</@if>


<@if VERSION = "A3">

<@assign CTA = "brown">
<@assign CTA2 = "grey">

</@if>

我无法将属于同一字段的值放入同一对象中。我得到的结果是创建了具有相同字段的多个对象。

期望的输出

[
 { VERSION : 
   [
    { A1:
     [
      { CTA: 'blue',
        CTA2: 'green',
      },
      A2:
     [
      { CTA: 'red',
        CTA2: 'yellow',
      },
      A3:
     [
      { CTA: 'brown',
        CTA2: 'grey',
      },
     ],
    },
  ],
 },
]

我需要搜索文本中的字段和值并将它们转换为对象。我无法将属于同一字段的值放入同一对象中。我得到的结果是创建了具有相同字段的多个对象。

javascript jquery arrays object regexp-replace
1个回答
0
投票

将其解析为 HTML,遍历元素并构建你梦想的对象:

const dom = new DOMParser().parseFromString(`<@if VERSION = "A1">

<@assign CTA = "blue">
<@assign CTA2 = "green">

<@elseif VERSION = "A2">

<@assign CTA = "red">
<@assign CTA2 = "yellow">

</@if>


<@if VERSION = "A3">

<@assign CTA = "brown">
<@assign CTA2 = "grey">

</@if>`.replaceAll('<@', '<').replaceAll('</@', '</'), 'text/html');

const walk =  node => {
  console.log(node.tagName);
  console.log(...[...node.attributes].map(a => a.name + ': ' + a.value));
  [...node.children].forEach(walk);
}

walk(dom.body);

© www.soinside.com 2019 - 2024. All rights reserved.