通过javascript删除json中相邻的重复数字

q3aa0525  于 2023-02-15  发布在  Java
关注(0)|答案(2)|浏览(150)

我的json:

{ "question_1": 
  { "type"  : "string"
  , "title" : "1. 1. What did he want to make for dinner?"
  , "enum": 
    [ " a.) He wanted to make some salad and spaghetti"
    , " b.) He wanted to make some pasta salad"
    ] 
  , "required": false
  } 
, "question_2": 
  { "type": "string"
  , "title": "2. 2. Did he have the ingredients to make dinner?"
  , "enum": 
    [ " a.) Yes, he had the ingredients"
    , " b.) No, he didn't have the ingredients"
    ] 
  , "required": false
  } 
, "question_3": 
  { "type"  : "string"
  , "title" : "3. 3. Where did he go shopping?"
  , "enum": 
    [ " a.) He went to Albertsons"
    , " b.) He went to Albertos"
    ] 
  , "required": false
  } 
}

在我的json中有许多数字彼此相邻并且重复
例如:

1. 1. => 1.
2. 2. => 2.
3. 3. => 3.

等等
我如何删除此重复项?
我想删除json中相邻的重复数字

b4lqfgs4

b4lqfgs41#

你可以用正则表达式替换它,使用分组引用((\d)周围的括号形成一个小数组,\1引用它)将确保你不会删除像“1.2.”这样的数字,并允许你在替换过程中引用它:

const data =
  { "question_1": 
    { "type"  : "string"
    , "title" : "1. 1. What did he want to make for dinner?"
    , "enum": 
      [ " a.) He wanted to make some salad and spaghetti"
      , " b.) He wanted to make some pasta salad"
      ] 
    , "required": false
    } 
  , "question_2": 
    { "type": "string"
    , "title": "2. 2. Did he have the ingredients to make dinner?"
    , "enum": 
      [ " a.) Yes, he had the ingredients"
      , " b.) No, he didn't have the ingredients"
      ] 
    , "required": false
    } 
  , "question_3": 
    { "type"  : "string"
    , "title" : "3. 3. Where did he go shopping?"
    , "enum": 
      [ " a.) He went to Albertsons"
      , " b.) He went to Albertos"
      ] 
    , "required": false
    } 
  };

Object.values(data).forEach(v => v.title = v.title.replace(/(\d)\. \1\./, '$1.'))
console.log(Object.values(data).map(v => v.title))
yi0zb3m4

yi0zb3m42#

如果它实际上是JSON(您将使用JSON.parse解析它),则可以使用可选的reviver参数。

复苏剂

如果是函数,则指定解析最初生成的每个值在返回之前如何转换。不可调用的值将被忽略。函数使用以下参数调用:

按键

与值关联的键。

数值

分析生成的值。

const JSONString = `{
  "question_1": {
    "type": "string",
    "title" : "1. 1. What did he want to make for dinner?"
  },
  "question_2": {
    "type": "string",
    "title": "2. 2. Did he have the ingredients to make dinner?"
  } 
}`;

console.log(
  JSON.parse(JSONString, (key, value) => typeof value === 'string' ? value.replace(/(\d)\. \1\./, '$1.') : value)
)

扩展Moritz Ringler的解决方案。

相关问题