arrays - 使用 Lodash 深度串联嵌套数组对象值

标签 arrays nested concatenation 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 来实现这一点吗?

最佳答案

我的解决方案:

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/

关于arrays - 使用 Lodash 深度串联嵌套数组对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44326116/

相关文章:

javascript - 如何使用过滤器设置过滤数组?

c++ - 将多维数组随机化(洗牌)到​​另一个二维数组中

python - 如何在 Pandas 中将嵌套列表转换为 DataFrame

javascript - 带有dimple.js图表​​的嵌套JSON对象数据

javascript - 使用 gulp 缩小和连接( Angular )网络应用程序的完整工作流程

java - 使用 for 循环连接构建字符串名称

PHP/MySQL : How do a concatenate a variable in a mysql query?

c++ - 无法删除类的析构函数中指向数组的成员指针

c++ - "p"数组如何使用 C++ std::normal_distribution 在以下代码中存储值?

node.js - 使用 MongoDB 4.0 查找函数返回匹配元素