映射(修改)深度嵌套的数组和对象结构
Mapping (modifying) a deeply nested structure of arrays and objects
我有一个深度嵌套的对象数组(列表)。每个对象都有一个数组,可以是空的,也可以包含另一个对象。我需要通过它们进行映射并输出一个结果,该结果将表示由每个项目的名称值组成的字符串。
结果应该是'name 1, name 2, name 3'。
到目前为止我已经有了这个,但我绝对没有得到我需要的东西:
const list = [
{id: 1, Item: []},
{id: 2, Item: [{name: 'name1'}]},
{id: 3, Item: [{name: 'name2'}, {name: 'name3'}]},
{id: 4, Item: []}
];
const getNames = (list) => {
const list = [];
_.forEach(list, (child) => {
list.push(child.Item);
});
const filteredList = list.filter(value => JSON.stringify(value) !== '[]');
const mappedList = _.map(filteredList, (el) => {
return el.name;
});
return _.join(mappedList, ', ');
};
const result= getNames(list);
//expected output: 'name 1, name 2, name 3' (string)
有什么想法吗?
你不需要 lodash,可以使用 .reduce()
和 .map()
const list = [
{id: 1, Item: []},
{id: 2, Item: [{name: 'name1'}]},
{id: 3, Item: [{name: 'name2'}, {name: 'name3'}]},
{id: 4, Item: []}
];
const getNames = (arr) => {
const names = arr.reduce((acc, {Item})=>[
...acc,
...Item.map(({name})=> name)
], []);
return names.join(', ');
}
console.log(getNames(list));
关于您的代码的一些反馈:您有名为 list
的冲突对象 - 它是一个全局变量,getNames()
的参数和该函数内的局部范围变量。 _.forEach
遍历一个空的局部范围变量而不是参数。注意变量名冲突
我有一个深度嵌套的对象数组(列表)。每个对象都有一个数组,可以是空的,也可以包含另一个对象。我需要通过它们进行映射并输出一个结果,该结果将表示由每个项目的名称值组成的字符串。
结果应该是'name 1, name 2, name 3'。
到目前为止我已经有了这个,但我绝对没有得到我需要的东西:
const list = [
{id: 1, Item: []},
{id: 2, Item: [{name: 'name1'}]},
{id: 3, Item: [{name: 'name2'}, {name: 'name3'}]},
{id: 4, Item: []}
];
const getNames = (list) => {
const list = [];
_.forEach(list, (child) => {
list.push(child.Item);
});
const filteredList = list.filter(value => JSON.stringify(value) !== '[]');
const mappedList = _.map(filteredList, (el) => {
return el.name;
});
return _.join(mappedList, ', ');
};
const result= getNames(list);
//expected output: 'name 1, name 2, name 3' (string)
有什么想法吗?
你不需要 lodash,可以使用 .reduce()
和 .map()
const list = [
{id: 1, Item: []},
{id: 2, Item: [{name: 'name1'}]},
{id: 3, Item: [{name: 'name2'}, {name: 'name3'}]},
{id: 4, Item: []}
];
const getNames = (arr) => {
const names = arr.reduce((acc, {Item})=>[
...acc,
...Item.map(({name})=> name)
], []);
return names.join(', ');
}
console.log(getNames(list));
关于您的代码的一些反馈:您有名为 list
的冲突对象 - 它是一个全局变量,getNames()
的参数和该函数内的局部范围变量。 _.forEach
遍历一个空的局部范围变量而不是参数。注意变量名冲突