使用Lodash深度嵌套数组对象值

德里玛

我有一个对象数组,每个对象可能包含子对象,这是具有相同结构的另一个数组。我想将每个对象的值连接到以字符分隔的字符串列表中。

例如:

var array = [{
    "text": "one",
    "children": [
      {
        "text": "two",
        "children": [
          {
            "text": "foo"
          },
          {
            "text": "bar"
          },
          {
            "text": "baz"
          }
        ]
      },
      {
        "text": "three",
        "children": [
          {
            "text": "foo"
          },
          {
            "text": "bar"
          },
          {
            "text": "baz"
          }
        ]
      }
    ]
}, {
    "text": "two",
    "children": [
      {
        "text": "hello",
        "children": [
          {
            "text": "world"
          },
          {
            "text": "planet"
          }
        ]
      }
    ]
}];

将导致:

[
    "one two foo",
    "one two bar",
    "one two baz",
    "one three foo",
    "one three bar",
    "one three baz",
    "two hello world",
    "two hello planet"
];

使用Lodash有什么办法可以实现?

米哈伊尔·沙布里科夫(Mikhail Shabrikov)

我的解决方案:

function concatString(currentString, object) {
  let string = currentString;

  if (object.text) {
    string = string + ' ' + object.text;
  }

  if (object.children) {
    string = object.children.map(item => concatString(string, item));
  }

  return string;
}

const result = _.flattenDeep(array.map(arrayItem => concatString('', arrayItem)));

https://jsfiddle.net/tqcj18so/1/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章