【问题标题】:Clone array with spread operator and add inline使用扩展运算符克隆数组并添加内联
【发布时间】:2017-06-12 17:21:23
【问题描述】:

有了一个对象,我可以像这样克隆和添加:

   let newObject = {
      ...obj,
      [key]: { 
         ...obj[key],
         thing: true }
   }

因此,这会将一些对象添加到数组中,然后更新一个对象的属性。 我知道要更新的项目索引,但不想覆盖现有属性。

现在我想对数组做同样的事情:

   let newArray = [
     ...arr,
     [key]: { 
         ...arr[key],
         thing: true }
   ]

这可能与上述相同。

但这不起作用。

{key}:thing 应该工作吗?我记得在某处读过这个,也许是它的 ES7?

我能做到:

   let newArray = arr.map((item, key) => key === index ? { ...item, thing: true } : item);

但我希望语法更简洁。如果没有类似的语法,我会接受 no。

【问题讨论】:

  • 不,除非你想在数组中追加/前置一个项目,否则使用map。或者用两个切片展开数组。
  • 你混淆了数组和对象。
  • [key]: thing 不是数组元素。
  • 我已经更新了示例以澄清
  • ... is not an operator! 看起来您使用的是 experimental 扩展属性,而不是数组扩展。

标签: javascript ecmascript-next


【解决方案1】:

你可以使用Object.assign():

const arr = [{ a: 1 }, { b: 1 }, { c: 1 }];
const index = 1;

const newArr = Object.assign([], arr, { [index]: { ...arr[index], thing: true } });
console.log(newArr);

【讨论】:

    【解决方案2】:

    数组没有键,因此您使用的语法不起作用。它是一个对象数组吗?如果是这样……

    编辑 - 根据您的评论,试试这个:

    // if you know the index of the object you'd like to modify
    let newArray = [
         ...arr
    ]
    newArray[idx][key] = thing
    
    // if you don't know the index
    let newArray = [
         ...arr
    ]
    newArray.map((el) => {
        if (/* YOUR LOGIC HERE TO DETERMINE IF THIS IS THE OBJECT TO MODIFY! */) {
            return el[key] = thing
        } else {
            return el
        }
    })
    
    // if you want it done in one function...
    let newArray = []
    arr.map((el) => {
        if (el[key]) {
            newArray.push(Object.assign({}, { [key]: thing }))
            return el
        } else {
            newArray.push(Object.assign({}, el))
            return el
        }
    })
    

    【讨论】:

    • 我需要访问数组中特定对象的索引,并且仅在将其插入新数组后更新该对象的属性。
    • 我确信 OP 知道这可以通过这种方式完成,但我认为他们正在寻找单行(即单个表达式)解决方案。
    • @TrySpace,我不认为它可以在一个简洁的功能中完成。你需要做的事情太多了:1)复制一个数组; 2)检查数组的每个元素,看看它是否与您想要的某个对象匹配; 3)修改所需的元素。我能想到的最好的例子是我在上面的代码中给出的第三个例子。
    猜你喜欢
    • 2020-03-01
    • 2021-09-02
    • 2018-03-31
    • 2018-05-19
    • 2019-10-14
    • 2016-06-12
    • 2019-06-29
    • 2017-10-15
    • 2017-09-26
    相关资源
    最近更新 更多