返回使用扩展运算符修改了某些键的变异对象

时间:2019-04-14 18:02:28

标签: javascript reactjs redux spread

在下面的对象中,我想将data [1]的val的值增加1,并使所有内容保持不变,如何实现?

const state = 
    {
        "data": [{
                "val": 1,
                "other": 10
            },
            {
                "val": 11,
                "other": 100
            },
            {
                "val": 100,
                "other": 1000
            }
        ]
    }

我希望变异的对象像这样-

{
    "data": [{
            "val": 1,
            "other": 10
        },
        {
            "val": 10,
            "other": 100
        },
        {
            "val": 100,
            "other": 1000
        }
    ]
}

我知道我可以像这样直接更改值-state.data[1].val = state.data[1].val+1,但是我想使用扩展运算符来实现相同的值,是否可以使用扩展运算符来实现? 像这样的东西

const mutatedState = {
        ...state,
        data: [...state.data]
}

3 个答案:

答案 0 :(得分:3)

从对象中取出data。并像这样使用

const state = { "data": [{ "val": 1, "other": 10 }, { "val": 11, "other": 100 }, { "val": 100, "other": 1000 } ] }
    
const {data} = state;         
let res = {
            ...state,
            data:[
                    data[0],
                    {...data[1],val:data[1].val+ 1},
                    ...data.slice(2)
                 ]
          }
 
console.log(result)

答案 1 :(得分:2)

您可以分配部分数组/对象。

public partial class UIItem : UserControl {

    public UIItemViewModel Model => DataContext as UIItemViewModel;

    public UIItem() { }

    public UIItem(UIItemViewModel model) {
        InitializeComponent();
        DataContext = model;
    }
}
var object = { data: [{ val: 1, other: 10 }, { val: 10, other: 100 }, { val: 100, other: 1000 }] },
    result = {
        ...object,
        data: Object.assign(
            [...object.data],
            {
                1: Object.assign(
                    {},
                    object.data[1],
                    { val: object.data[1].val + 1 }
                )
            }
        )
    };

console.log(result);

答案 2 :(得分:0)

在一些功能助手的帮助下,这实际上非常优雅:

 const mapOne = (index, mapper) => array => array.map((it, i) => i === index ? mapper(it) : it);
 const lens = (key, mapper) => obj => ({ ...obj, [key]: mapper(obj[key]) });

 // somewhere
 this.setState(mapOne(1, lens("val", it => it + 1)));