简体   繁体   English

从嵌套对象数组中递归创建字符串?

[英]Recursively create string out of array of nested objects?

Ultimately, I'm not sure if this is the right way to go about this, so I'm open to suggestions. 最终,我不确定这是否是正确的解决方法,因此我愿意提出建议。

What I'm trying to do is write a recursive function that is called while iterating over each element of an array of objects. 我想做的是编写一个递归函数,该函数在对对象数组的每个元素进行迭代时被调用。 The function should take the array element, recursively iterate over its values and nested objects. 该函数应采用array元素,以递归方式遍历其值和嵌套对象。

So, for example, the function might be called while iterating over an array of nested objects like so... 因此,例如,可以在像这样的嵌套对象array进行迭代时调用该函数。

arrayOfNestedObjects.map(el => objectValues(el))

I'm using https://jsonplaceholder.typicode.com/ to fetch an array of objects of this shape... 我正在使用https://jsonplaceholder.typicode.com/来获取这种形状的对象数组...

{
  id: 10,
  name: 'Clementina DuBuque',
  username: 'Moriah.Stanton',
  email: 'Rey.Padberg@karina.biz',
  address: {
    street: 'Kattie Turnpike',
    suite: 'Suite 198',
    city: 'Lebsackbury',
    zipcode: '31428-2261',
    geo: {
      lat: '-38.2386',
      lng: '57.2232'
    }
  },
  phone: '024-648-3804',
  website: 'ambrose.net',
  company: {
    name: 'Hoeger LLC',
    catchPhrase: 'Centralized empowering task-force',
    bs: 'target end-to-end models'
  }
}

What I want to return from my recursive function is a single, concatenated string of all values for each element of the array, including all values from any nested objects, like so from the above example.. 我想从我的递归函数返回是一切价值的阵列中的每个元素,包括任何嵌套对象的所有值的单个,连接字符串,像这样从上面的例子..

"10clementinadubuquemoriah.stantonrey.padberg@karina.bizkattieturnpikesuite198lebsackbury31428-2261-38.238657.2232024-648-3804ambrose.nethoegerllccentralizedempoweringtask-forcetargetend-to-endmodels"

The problem I'm having is that there seems to be a final call of my recursive function that returns a string omitting all values from some of the nested objects. 我遇到的问题是,似乎对递归函数进行了最后一次调用,该函数返回的字符串忽略了一些嵌套对象中的所有值。 Here's what I have so far for my function... 到目前为止,这是我的职责...

function objectValues(value, ...args) {
  let string = args;
  Object.values(value).forEach((val, i) => {
    if (typeof val === 'object' && val !== null) {
      objectValues(val, string);
    } else {
      string += val
        .toString()
        .replace(/\s/g, '')
        .toLowerCase();
        console.log(string);
    }
  });
  return string;
}

Logging string inside of the else clause shows me the string I want, but logging string just above the return shows me the erroneous string missing the values from the company object. 登录string的内部else条款显示我我想要的字符串,但记录string只是上面return显示我的错误字符串中缺少从价值company对象。 It must be something simple that I'm missing about how I've set up the recursion. 关于设置递归的过程,一定缺少一些简单的东西。 Thanks for any suggestions! 感谢您的任何建议!

The ...args parameter is making things more complicated than they have to be. ...args参数使事情变得复杂得多。 If ...args is an array , renaming it let string = args is pretty confusing - especially, as you can see later, when you do string += ... (but += doesn't make much sense on arrays ) 如果...args是一个数组 ,重命名它let string = args相当混乱-特别是,正如您稍后会看到的,当您执行string += ... (但是+=数组没有多大意义)

Instead, just declare an empty string at the beginning of the function, concatenate it when necessary, and return it at the end of the function. 相反,只需在函数的开头声明一个空字符串,在必要时return其连接,然后在函数的末尾将其return reduce is a bit more appropriate than forEach when you're condensing an array into a single value, such as a string: 当您将数组压缩为单个值(例如字符串)时, reduceforEach更合适:

 const value={id:10,name:'Clementina DuBuque',username:'Moriah.Stanton',email:'Rey.Padberg@karina.biz',address:{street:'Kattie Turnpike',suite:'Suite 198',city:'Lebsackbury',zipcode:'31428-2261',geo:{lat:'-38.2386',lng:'57.2232'}},phone:'024-648-3804',website:'ambrose.net',company:{name:'Hoeger LLC',catchPhrase:'Centralized empowering task-force',bs:'target end-to-end models'}} function objectValues(value) { return Object.values(value).reduce((string, val, i) => string + ( (typeof val === 'object' && val !== null) ? objectValues(val) : val .toString() .replace(/\\s/g, '') .toLowerCase() )); } console.log(objectValues(value)); 

Another option would be to exploit JSON.stringify 's naturally recursive nature: 另一个选择是利用JSON.stringify的自然递归性质:

 const value={id:10,name:'Clementina DuBuque',username:'Moriah.Stanton',email:'Rey.Padberg@karina.biz',address:{street:'Kattie Turnpike',suite:'Suite 198',city:'Lebsackbury',zipcode:'31428-2261',geo:{lat:'-38.2386',lng:'57.2232'}},phone:'024-648-3804',website:'ambrose.net',company:{name:'Hoeger LLC',catchPhrase:'Centralized empowering task-force',bs:'target end-to-end models'}} function objectValues(value) { let string = ''; JSON.stringify(value, (_, val) => { if (typeof val === 'string') string += val.replace(/\\s/g, '').toLowerCase(); return val; }); return string; } console.log(objectValues(value)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM