英文:
Replacing an array element with elements of another array in state
问题
const [obj, setObj] = useState({a:[1, "x", 4]});
const arr = [2, 3];
在调用 setObj 函数之后,我希望将“a”数组中第二个索引位置的值(即"x")替换为 arr 数组中的内容,因此输出应该是:
{a:[1, 2, 3, 4]}
另外,arr 数组的内容并不是预先确定的,可以在调用函数之前进行更改。
我尝试复制 obj,并使用 splice 方法修改数组,但由于 setObj 函数绑定到 onChange 事件并且重复触发,所以它没有起作用。
英文:
const [obj, setObj] = useState({a:[1, "x", 4]});
const arr = [2, 3];
After I fire the setObj function, I want whatever's in the second index of the "a" array that is "x" to be replaced with whatever's inside the arr, so the output should be:
{a:[1, 2, 3, 4]}
Also the contents of the arr are not predetermined and can change before the function is fired.
I tried copying the obj and modifying the array using the splice method, but it didn't work because the setObj function is bound to an onChange event and is fired repeatedly.
答案1
得分: 1
const preState = {
a: [1, "x", 4]
}
const arr = [2, 3];
const nextState = {
a: preState.a.flatMap(v => v === 'x' ? arr : v)
}
console.log('nextState: ', nextState)
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const preState = {
a: [1, "x", 4]
}
const arr = [2, 3];
const nextState = {
a: preState.a.flatMap(v => v === 'x' ? arr : v)
}
console.log('nextState: ', nextState)
<!-- end snippet -->
答案2
得分: 1
使用扩展运算符 ...
对 obj.a
进行解构。下面的代码将 x
替换为 arr
的内容。查看此链接以了解扩展运算符的工作原理:https://www.geeksforgeeks.org/javascript-spread-operator/
const [obj, setObj] = useState({a:[1, "x", 4]});
const arr = [2, 3];
const [one,two,...rest]=obj.a;
setObj({a:[one,...arr,...rest]});
英文:
Use the spread opeartor ...
to destructure obj.a
. The below code replaces x with the contents of arr
. Check this link for details on how spread operator works: https://www.geeksforgeeks.org/javascript-spread-operator/
const [obj, setObj] = useState({a:[1, "x", 4]});
const arr = [2, 3];
const [one,two,...rest]=obj.a;
setObj({a:[one,...arr,...rest]});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论