如何在复杂性方面优化我的 JS 代码

贾森·瓦尔盖塞

我有 2 个数组:

user = [
  { id: 33, first_name: 'Alex', last_name: 'Shelly' },
  { id: 23, first_name: 'Mike', last_name: 'Marley' }
]

selectedNotes = [
  { employee_id: 33, notes: 'test' },
  { employee_id: 109, notes: 'test1' }
]

我试图找到firstnamelastname用户的,其id与比赛employee_idselectedNotes的数组。(例如,上述案例中的 Alex Shelly)。

我拥有的:

for (let i = 0; i < user.length; i++) {
  for (let j = 0; j < selectedNotes.length; j++) {
    if (user[i].id == selectedNotes[j].employee_id) {
      selectedNotes.splice(j, 0, {
        by_name: user[i].first_name + ' ' + user[i].last_name
      }); // adding a new property in the array if the id matches
    }
  }
}

在优化方面有没有更好的方法来做到这一点?

穆卡格格利

我只会做一个map()和一个Object.assign()

const user = [{
    id: 33,
    first_name: "Alex",
    last_name: "Shelly"
  },
  {
    id: 23,
    first_name: "Mike",
    last_name: "Marley"
  }
]

const selectedNotes = [{
  employee_id: 33,
  notes: 'test'
}, {
  employee_id: 109,
  notes: 'test1'
}]

// use map() to iterate over selectedNotes, and for each value
// in selectedNotes assign the values of an object from user,
// where we get the values by filtering the user array for the
// id of the current element in the iteration of selectedNotes

// TL;DR: run over selectedNotes, filter for the id value in
// user and add the resulting object's key-value pairs to the
// actual selectedNotes item
const selected = selectedNotes.map(e => Object.assign(e, user.filter(el => el.id === e.employee_id)[0]))

// output the resulting array of objects
console.log(selected)

现在您拥有一组对象中的所有数据,因此您只需根据您要查找的值对其进行过滤。

参考:

Array.prototype.map(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Object.assign(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章