【问题标题】:search and replace string on title key nested object vue js在标题键嵌套对象vue js上搜索和替换字符串
【发布时间】:2021-03-12 11:13:21
【问题描述】:

我有一个包含多个键的嵌套对象,这些键还包括标题和子项。 children 也是具有标题和子键的对象数组。 (它们看起来像一棵树) 如何搜索和替换一个单词或标题值的一部分?

const object = {
    id: 'uuid',
    title: 'hello You',
    type: number,
    visibility: true,
    children: [
        {
            id: 'uuid',
            title: 'You don't have any comments...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
        },
        {
            id: 'uuid',
            title: 'You your problem is not with json...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
       }
    ],
    key1: {...},
    key2: [{...}]
}

搜索you并替换标题上的world

output = {
    id: 'uuid',
    title: 'hello world',
    type: number,
    visibility: true,
    children: [
        {
            id: 'uuid',
            title: 'world don't have any comments...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
        },
        {
            id: 'uuid',
            title: 'world your problem is not with json...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
       }
    ],
    key1: {...},
    key2: [{...}]
}

【问题讨论】:

    标签: javascript vue.js search


    【解决方案1】:

    您可以尝试使用 recursive 策略来查找数组中的任何键,也可以搜索其子项。

    function recursive (newArray) {
      newArray.map(obj => {
        if (obj.title) {
          obj.title = obj.title.replace(/You/g, 'world')
        }
        if (obj.children) {
          return recursive (obj.children)
        }
      })
      return newArray
    }
    

    使用函数

    let arr = [object]
    
    recursive(arr)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 2018-01-02
      • 1970-01-01
      相关资源
      最近更新 更多