我有一个对象数组,每个对象可能包含子节点,这是另一个具有相同结构的数组。我想将每个对象的值连接成一个用字符分隔的字符串列表。
例如:
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有什么办法可以实现吗?
答案 0 :(得分:1)
您可以递归使用Array#map
来收集字符串,然后使用Array#concat
展平结果。
ES6:
const 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"}]}]}];
const collect = (arr, pre = '') => {
return [].concat([], ...arr.map((item) => {
const label = `${pre} ${item.text}`.trim();
return item.children ? collect(item.children, label) : label;
}));
}
const result = collect(array);
console.log(result);

ES5:
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"}]}]}];
function collect (arr, pre) {
return [].concat.apply([], arr.map(function(item) {
var label = (pre + ' ' + item.text).trim();
return item.children ? collect(item.children, label) : label;
}));
}
var result = collect(array, '');
console.log(result);

答案 1 :(得分:1)
我的解决方案:
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)));