我正在嘗試遍歷一個陣列并在找到它時更新它。我已經通過 Google 和 SO 進行了搜索,但我想我沒有使用正確的關鍵字來做到這一點。
問題
我有以下物件:
const form = {
uuid: "ff17fd11-3462-4111-b083-7ff36b391c61",
type: "form",
items: [
{
uuid: "0b2dcf80-a376-4b3d-9491-0875ec24d6f7",
type: "page",
items: [
{
uuid: "23a8db85-4125-43db-ae04-d1243738972c",
title: "Prepared by",
},
{
uuid: "fb3898e0-c250-4dde-8b5c-cd2c99d181e9",
title: "Completed at",
}
],
params: { header: true, collapsed: true }
},
{
title: "",
uuid: "e0d9d8c4-c064-4088-aad3-235b6ea1a6a1",
type: "page",
items: [
{
uuid: "73f97b99-9788-4748-82c6-7b62169f44fe",
title: "you have been rickrolled",
},
{
uuid: "46e7264c-7e95-4bbf-a4e7-7b7ab2d1ad88",
type: "conditional_section",
items: [
{
uuid: "58e5e845-d18e-4c7e-9739-a387b8144d3c",
params: {
title: null,
},
}
],
],
}
]
};
給定以下物件,我想在陣列中找到該物件(由 標識uuid)并將其替換為新物件:
?? Heres the uuid that identifies the unique element in the array
const updatedObject = { uuid: "58e5e845-d18e-4c7e-9739-a387b8144d3c", params: { title: "new title" } };
findFormItem(form.items, updatedObject);
到目前為止我嘗試過的
我創建了一個遞回函式來更新陣列,但由于某種原因,該專案沒有被更新:
const findFormItem = (arr, item, parent = null) =>
arr.reduce((acc, _item) => {
if (acc) {
return acc;
}
if (_item.uuid === item.uuid) {
_item = item;
}
if (_item.items) {
return findFormItem(_item.items, item, _item);
}
return acc;
}, null);
題
如何在不必回傳新副本的情況下更新陣列/物件?我正在尋找一種不會改變物件形式的解決方案。物件應保持原樣,僅更新傳遞給findFormItem函式的值
密碼箱
uj5u.com熱心網友回復:
如果您想要更改原始陣列,您可以使用forEach并替換給定的物件index:
const findFormItem = (arr, item) => {
arr.forEach((element, index, arr) => {
if (element.uuid === item.uuid) {
arr[index] = item;
}
if (element.items) {
findFormItem(element.items, item);
}
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436813.html
標籤:javascript 数组
