将键值对添加到数组中的所有对象 [英] Add key value pair to all objects in array

查看:23
本文介绍了将键值对添加到数组中的所有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为数组中的所有对象添加一个 key:value 参数.

I wanted to add a key:value parameter to all the objects in an array.

例如:

var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];

现在我想向所有对象添加一个新参数 isActive ,因此结果数组将如下所示.

Now I wanted to add a new parameter, isActive to all the objects so the resulting array will look like.

例如:

    [{
    name: 'eve',
    isActive: true
}, {
    name: 'john',
    isActive: true
}, {
    name: 'jane',
    isActive: true
}]

我总是可以遍历数组并插入一个键值对.但是想知道是否有更好的方法来做到这一点

I can always loop through the array and insert a key,value pair. But was wondering if there was a better way to do so

推荐答案

map() 函数是这种情况的最佳选择

The map() function is a best choice for this case

tl;dr - 这样做:

const newArr = [
  {name: 'eve'},
  {name: 'john'},
  {name: 'jane'}
].map(v => ({...v, isActive: true}))

map()函数不会修改初始数组,而是创建一个新数组.这也是保持初始数组不变的好习惯.

The map() function won't modify the initial array, but creates a new one. This is also a good practice to keep initial array unmodified.

替代方案:

const initialArr = [
      {name: 'eve'},
      {name: 'john'},
      {name: 'jane'}
    ]

const newArr1 = initialArr.map(v => ({...v, isActive: true}))
const newArr2 = initialArr.map(v => Object.assign(v, {isActive: true}))

// Results of newArr1 and newArr2 are the same

添加键值对有条件

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr1 = arr.map(v => ({...v, isActive: v.value > 1}))

如果条件为假我根本不想添加新字段怎么办?

What if I don't want to add new field at all if the condition is false?

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr = arr.map(v => {
  return v.value > 1 ? {...v, isActive: true} : v 
})

添加WITH修改初始数组

Adding WITH modification of the initial array

const initialArr = [{a: 1}, {b: 2}]
initialArr.forEach(v => {v.isActive = true;});

这可能不是最好的主意,但在现实生活中有时这是唯一的方法.

This is probably not a best idea, but in a real life sometimes it's the only way.

问题

  • 我应该使用扩展运算符(...) 还是Object.assign,它们之间有什么区别?
  • Should I use a spread operator(...), or Object.assign and what's the difference?

我个人更喜欢使用 spread 运算符,因为我认为它在现代网络社区中使用范围更广(尤其是 react 的开发人员喜欢它).但是你可以自己检查差异:link(有点自以为是和旧的,但仍然)

Personally I prefer to use spread operator, because I think it uses much wider in modern web community (especially react's developers love it). But you can check the difference yourself: link(a bit opinionated and old, but still)

  • 我可以使用 function 关键字代替 => 吗?

当然可以.粗箭头 (=>) 函数与 this 的作用略有不同,但对于这种特殊情况,它并不那么重要.但是胖箭头的功能更短,有时作为回调效果更好.因此,胖箭头函数的使用是更现代的方法.

Sure you can. The fat arrow (=>) functions play a bit different with this, but it's not so important for this particular case. But fat arrows function shorter and sometimes plays better as a callbacks. Therefore the usage of fat arrow functions is more modern approach.

  • ma​​p 函数内部实际发生了什么:.map(v => ({...v, isActive: true})?

Map 函数按数组元素进行迭代,并为每个元素应用回调函数.该回调函数应该返回一些将成为新数组元素的东西.我们告诉 .map() 函数如下:获取当前值(v 这是一个对象),从 v 中取出所有键值对code> 并将其放入一个新对象({...v})中,但还要添加属性 isActive 并将其设置为 true({...v, isActive: true}) 然后返回结果.顺便说一句,如果原始对象包含 isActive 归档,它将被覆盖.Object.assign 以类似的方式工作.

Map function iterates by array's elements and apply callback function for each of them. That callback function should return something that will become an element of a new array. We tell to the .map() function following: take current value(v which is an object), take all key-value pairs away from v andput it inside a new object({...v}), but also add property isActive and set it to true ({...v, isActive: true}) and then return the result. Btw, if original object contains isActive filed it will be overwritten. Object.assign works in a similar way.

  • 我可以一次添加多个字段吗

是的.

[{value: 1}, {value: 1}, {value: 2}].map(v => ({...v, isActive: true, howAreYou: 'good'}))

  • 我不应该在 .map() 方法中做什么
  • 你不应该做任何副作用[link 1, 链接 2],但显然你可以.

    You shouldn't do any side effects[link 1, link 2], but apparently you can.

    另请注意,map() 遍历数组的每个元素并为每个元素应用函数.所以如果你在里面做一些重的事情,你可能会很慢.这个(有点 hacky)解决方案在某些情况下可能更有效率(但我认为你不应该更多地应用它然后一生一次).

    Also be noticed that map() iterates over each element of the array and apply function for each of them. So if you do some heavy stuff inside, you might be slow. This (a bit hacky) solution might be more productive in some cases (but I don't think you should apply it more then once in a lifetime).

    • 我可以将地图的回调提取到单独的函数吗?

    当然可以.

    const arr = [{value: 1}, {value: 1}, {value: 2}]   
    const newArr = arr.map(addIsActive)
    
    function addIsActive(v) {
        return {...v, isActive: true}
    }
    

    • 旧的 good for 循环有什么问题?
    • for 没什么问题,你仍然可以使用它,它只是一个老派的方法,它更冗长,更不安全,并且改变了初始数组.不过你可以试试:

      Nothing is wrong with for, you can still use it, it's just an old-school approach which is more verbose, less safe and mutate the initial array. But you can try:

      const arr = [{a: 1}, {b: 2}]
      for (let i = 0; i < arr.length; i++) {
       arr[i].isActive = true
      }
      

      • 我还应该学习什么
      • 学习好以下方法会很聪明 map(), filter(), reduce(), forEach(),和 find().这些方法可以解决你通常想用数组做的 80% 的事情.

        It would be smart to learn well following methods map(), filter(), reduce(), forEach(), and find(). These methods can solve 80% of what you usually want to do with arrays.

        这篇关于将键值对添加到数组中的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆