首页 > 解决方案 > 从嵌套对象数组中递归创建字符串?

问题描述

最终,我不确定这是否是解决此问题的正确方法,所以我愿意接受建议。

我要做的是编写一个递归函数,在迭代对象数组的每个元素时调用该函数。该函数应采用数组元素,递归迭代其值和嵌套对象。

因此,例如,可能会在迭代array嵌套对象时调用该函数,如下所示......

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

我正在使用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'
  }
}

我想从我的递归函数返回的是一个单一的串联字符串,其中包含数组每个元素的所有值,包括来自任何嵌套对象的所有值,就像上面的例子一样..

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

我遇到的问题是我的递归函数似乎有一个最终调用,它返回一个字符串,省略了一些嵌套对象的所有值。这是我到目前为止的功能......

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;
}

string在子句内部记录else显示我想要的字符串,但string在上面记录return显示错误字符串缺少company对象中的值。关于我如何设置递归,我一定很简单。感谢您的任何建议!

标签: javascriptarraysrecursioniteration

解决方案


...args参数使事情变得比它们必须的更复杂。如果...args是一个数组,重命名它let string = args是相当混乱的——尤其是你稍后会看到,当你这样做时string += ...(但对数组+=没有多大意义)

相反,只需在函数的开头声明一个空字符串,必要时将其连接起来,然后return在函数的末尾进行连接。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));

另一种选择是利用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));


推荐阅读