用另一个数组的元素替换状态中的一个数组元素

huangapple go评论88阅读模式
英文:

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, &quot;x&quot;, 4]
}
const arr = [2, 3];

const nextState = {
  a: preState.a.flatMap(v =&gt; v === &#39;x&#39; ? arr : v)
}

console.log(&#39;nextState: &#39;, nextState)

<!-- end snippet -->

答案2

得分: 1

使用扩展运算符 ...obj.a 进行解构。下面的代码将 x 替换为 arr 的内容。查看此链接以了解扩展运算符的工作原理:https://www.geeksforgeeks.org/javascript-spread-operator/

const [obj, setObj] = useState({a:[1, &quot;x&quot;, 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, &quot;x&quot;, 4]});
const arr = [2, 3];
const [one,two,...rest]=obj.a;
setObj({a:[one,...arr,...rest]});

huangapple
  • 本文由 发表于 2023年6月25日 17:51:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76549800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定