量身定制ES6阵列过滤的结果

时间:2019-05-17 20:06:12

标签: javascript arrays ecmascript-6 filter

我有一个看起来像这样的数组:

userData:

[
{firstName:"sally", lastName:"yates", id:1},
{firstName:"bob", lastName:"ross", id:2}
]

petData:

[
{pet:"dog", ownerId:1}
{pet:"cat", ownerId:2}
]

我希望我的结果看起来像这样:

[
{pet:"dog", userId:1, userName:"sally yates"},
{pet:"cat", userId:2, userName:"bob ross"}
]

我可以执行过滤,但只能使用1个名称。获得名字和姓氏的合适方法是什么?

 petData.forEach(function(item) {
    var creator = _.pluck(
    _.filter(userData, {
    id: item.ownerId
    }),
    "first_name"
    );
    item["userName"] = creator;
  }

**抱歉,我必须保留forEach函数,因为其他开发人员的代码将其用于其他条件

5 个答案:

答案 0 :(得分:2)

您可以将用户移动到Map中并映射所有宠物。

const getName = ({ firstName, lastName } = {}) => [firstName, lastName].join(' ');

var userData = [{ firstName: "sally", lastName: "yates", id: 1 }, { firstName: "bob", lastName: "ross", id: 2 }],
    petData = [{ pet: "dog", ownerId: 1 }, { pet: "cat", ownerId: 2 }],
    users = new Map(userData.map(o => [o.id, o])),
    result = petData.map(({ pet, ownerId: userId }) => ({ pet, userId, userName: getName(users.get(userId)) }));
    
console.log(result);

答案 1 :(得分:1)

我将通过ID创建用户地图:

  const byID = new Map();

  for(const user of userData)
    byID.set(user.id, user);

现在,您可以轻松查找宠物主人并合并其名称:

 for(const pet of petData) {
   const owner = byID.get(pet.ownerId);
   pet.userName = owner.firstName + " " + owner.lastName;
   pet.userId = owner.id;
}

答案 2 :(得分:1)

一种解决方案是在pets的数组上使用Array.map(),并在map的每次迭代中,使用Array.find()来获取相关的person对象从另一个数组:

const persons = [
  {firstName:"sally", lastName:"yates", id:1},
  {firstName:"bob", lastName:"ross", id:2}
];

const pets = [
  {pet:"dog", ownerId:1},
  {pet:"cat", ownerId:2}
];

let res = pets.map(({pet, ownerId}) =>
{
    let {firstName, lastName} = persons.find(({id}) => id === ownerId);
    return {pet, userId: ownerId, userName: `${firstName} ${lastName}`};
});

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

这是另一个使用Array.reduce()Object.assign()的棘手版本:

const persons = [
  {firstName:"sally", lastName:"yates", id:1},
  {firstName:"bob", lastName:"ross", id:2}
];

const pets = [
  {pet:"dog", ownerId:1},
  {pet:"cat", ownerId:2}
];

let res = Object.values([...persons, ...pets].reduce((acc, {id, ownerId, pet, firstName, lastName}) =>
{
    let userId = id === undefined ? ownerId : id;
    let userName = `${firstName} ${lastName}`;
    acc[userId] = acc[userId] || {};
    Object.assign(acc[userId], {userId}, (id === undefined ? {pet} : {userName}));
    return acc;
}, {}));

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

答案 3 :(得分:1)

要获得预期结果,请使用以下使用地图和过滤器的选项

  1. 使用地图循环petData
  2. 使用petData ownerId过滤userData数组

let userData = [
{firstName:"sally", lastName:"yates", id:1},
{firstName:"bob", lastName:"ross", id:2}
]

let petData = [
{pet:"dog", ownerId:1},
{pet:"cat", ownerId:2}
]

console.log(petData.map(v => {
  let user = userData.filter(val => val.id === v.ownerId)[0]
  v["userName"] = user.firstName + ' ' + user.lastName;
  v["userId"] = v.ownerId;
  delete v.ownerId;
  return v
}))

选项2:根据有问题的要求使用forEach

let userData = [
{firstName:"sally", lastName:"yates", id:1},
{firstName:"bob", lastName:"ross", id:2}
]

let petData = [
{pet:"dog", ownerId:1},
{pet:"cat", ownerId:2}
]

let result =[]
petData.forEach(v => {
  let user = userData.filter(val => val.id === v.ownerId)[0]
  v["userName"] = user.firstName + ' ' + user.lastName;
  v["userId"] = v.ownerId;
  delete v.ownerId;
  result.push(v)
})
console.log(result)

答案 4 :(得分:0)

由于您实际上并不关心键的顺序,因此可以为用户使用<script src="https://f.vimeocdn.com/js/froogaloop2.min.js"></script> <iframe id="projectplayer" src="https://player.vimeo.com/video/336413453"></iframe> <script> iframe = $('#projectplayer')[0]; player = $f(iframe); player.api('setVolume',1); //reset volume </script> ,然后通过object literal来获得最终结果:

key/ownerId

这种方法比对每次pet迭代等进行过滤时更有效。