【问题标题】:Remove duplicate numbers next to each other in json by javascript通过javascript删除json中彼此相邻的重复数字
【发布时间】:2023-02-14 23:11:28
【问题描述】:

我的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 中彼此相邻的重复数字

【问题讨论】:

  • 这看起来不像 JSON(应该是一个字符串),它看起来像一个 JavaScript 对象字面量。但是,除此之外,是什么导致了数字的重复,是否可以解决这个问题而不是事后整理?

标签: javascript json


【解决方案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.'))
console.log(Object.values(data).map(v => v.title))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多