我有一个projects列表,如下所示:

projects = [{name: '1',
             agencies: ['USA', 'China']},
            {name: '2',
             agencies: ['Japan', 'Russia']}]


我想得到结果['USA', 'China', 'Japan', 'Russia'],当前我使用以下代码,但是我想知道是否有使用map函数的更好的解决方案(一行代码):

const agencies = [];
projects.forEach((project) =>
        project.agencies.forEach((agency) => {
            agencies.push(agency);
        })
);

最佳答案

这是完成此操作的简单方法:



const projects = [{
  name: '1',
  agencies: ['USA', 'China']
}, {
  name: '2',
  agencies: ['Japan', 'Russia']
}]

const agencies = [].concat(...projects.map(x => x.agencies));
console.log(agencies)

关于javascript - 使用映射从数组的数组创建新数组的更好方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48451621/

10-09 22:35