返回使用扩展运算符修改了一些键的变异对象
Returning mutated object with some key modified using spread operator
在下面的对象中,我想将 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]
}
从对象中取出 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)
您可以分配 array/objects 的部分内容。
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);
.as-console-wrapper { max-height: 100% !important; top: 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)));
在下面的对象中,我想将 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]
}
从对象中取出 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)
您可以分配 array/objects 的部分内容。
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);
.as-console-wrapper { max-height: 100% !important; top: 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)));