用第二个数组中的名称替换数组中的id

时间:2019-05-25 21:38:34

标签: javascript arrays angular object ecmascript-6

我在用id连接两个数组和对象并将第二个数组中的id替换为NAME时遇到了一些问题。例如,我有数组:

array1 = [
  {id: [1, 2], info: "xxx"},
  {id: [2, 3], info: "yyy"}
]

array2 = [
  {nameId: 1, name: "Miami"},
  {nameId: 2, name: "Wacanda"},
  {nameId: 3, name: "London"},
]

我想修改array1或创建新的array3,例如(使用ES6):

array1 = [
  {id: ["Miami", "Wacanda"], info: "xxx"},
  {id: ["Wacanda", "London"], info: "yyy"}
]

array3 = [
  {name: ["Miami", "Wacanda"], info: "xxx"},
  {name: ["Wacanda", "London"], info: "yyy"}
]

链接到快速编辑: https://stackblitz.com/edit/angular-lrnfrd?file=src%2Fapp%2Ftesting%2Ftesting.component.ts

3 个答案:

答案 0 :(得分:1)

一种可能的解决方案是首先使用Mapidsnames的{​​{1}}和array2之间生成一个Array.reduce()。然后,您可以在array1上使用Array.map()来获取所需的数据。请注意,在下一个示例中,我选择了第二个输出样本。

const array1 = [
  {id: [1, 2], info: "xxx"},
  {id: [2, 3], info: "yyy"}
];

const array2 = [
  {nameId: 1, name: "Miami"},
  {nameId: 2, name: "Wacanda"},
  {nameId: 3, name: "London"},
];

let nameFromId = array2.reduce(
    (acc, {nameId, name}) => (acc.set(nameId, name), acc),
    new Map()
);

let res = array1.map(({id, info}) => ({name: id.map(i => nameFromId.get(i)), info}));

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

不生成Map的另一种方法是在map()函数内使用Array.find()

let res = array1.map(
  ({id, info}) => ({name: id.map(i => array2.find(o => o.nameId === i).name), info})
);

答案 1 :(得分:0)

真的很简单-只需将嵌套的mapfind一起使用:

const array1 = [{id:[1,2],info:"xxx"},{id:[2,3],info:"yyy"}];
const array2 = [{nameId:1,name:"Miami"},{nameId:2,name:"Wacanda"},{nameId:3,name:"London"}];
const array3 = array1.map(({ id, info }) => ({ name: id.map(e => array2.find(({ nameId }) => nameId == e).name), info }));
console.log(array3);
.as-console-wrapper { max-height: 100% !important; top: auto; }

答案 2 :(得分:0)

这将生成您的第二个示例:

var array3 = array1.map(({ id, info }) => ({
    name: array2.filter(({ nameId }) => id.includes(nameId)).map(({ name }) => name),
    info
}));

首先,它对位于array1的ID列表中的nameId进行过滤,然后运行map以仅返回该名称。预期的输出将变为:

[
    {"name":["Miami","Wacanda"],"info":"xxx"},
    {"name":["Wacanda","London"],"info":"yyy"}
]