What is the shortest way to modify immutable objects using spread and destructuring operators

前端 未结 6 1134
无人及你
无人及你 2021-01-30 22:34

I\'m looking for a pure function, to modify my immutable state object. The original state given as parameter must stay untouched. This is especially useful when working with fra

6条回答
  •  春和景丽
    2021-01-30 23:21

    In a Map Function

    To do this process within a map function (remove an attribute and add a new attribute on each object), given an array of objects -

    const myArrayOfObjects = [
        {id: 1, keyToDelete: 'nonsense'},
        {id: 2, keyToDelete: 'rubbish'}
    ];
    

    Delete the attribute keyToDelete, and add a new key newKey with the value "someVar".

    myArrayOfObjects.map(({ keyToDelete, ...item}) => { ...item, newKey:'someVar'});
    

    Updating the array to

    [
        {id: 1, newKey:'someVar'},
        {id: 2, newKey:'someVar'}
    ]
    

    See this great post for more information on the deletion method.

提交回复
热议问题