Warm tip: This article is reproduced from serverfault.com, please click

javascript-搜索并替换标题键嵌套对象vue js上的字符串

(javascript - search and replace string on title key nested object vue js)

发布于 2020-11-30 14:10:36

我有一个包含几个键的嵌套对象,这些键还包括标题和子代。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: [{...}]
}
Questioner
Mohammad
Viewed
0
kusiaga 2020-12-01 11:47:52

你可以尝试使用递归策略在数组中查找任何键,也可以搜索其子级。

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)