這是我的數據結構:
[
0:
key1: value,
key2: value,
array:
0:
thisId: xxxxx,
thisValue: value,
1:
notThisId: someId,
notThisValue: value,
key3: value
1:
key1: value
key2: value
array:
0:
anotherId: id
anotherValue: value
key3: value
]
您好,我有一個查詢正在返回:
thisIdRef: xxxxx,
thisNewValue: newValue
是否可以將嵌套的“thisValue”更新為“thisNewValue”,其中“thisIdRef”等於“thisId”或“xxxxx”?
我在下面使用 findIndex 和 splice 做了類似的事情,但這是針對非嵌套鍵/值對的,我無法弄清楚如何找到嵌套 id,或者如果可能的話。
let newArray = oldArray;
const index = newArray.findIndex(post => post._id === editedPostId)
newArray.splice(index, 1, {
...newArray[index],
post: editedContent
})
非常感謝任何幫助。
我假設您要創建一個新數組,這樣原始數組及其嵌套結構不會發生變異。
這是您可以使用的函數:
function setDeep(original, editedPostId, editedContent) {
return original.map(obj => {
let i = obj.array.findIndex(item => item.thisId === editedPostId);
if (i == -1) return obj;
return {
...obj,
array: Object.assign([], obj.array, {
[i]: {
...obj.array[i],
thisId: editedPostId,
thisValue: editedContent
}
})
};
});
}
// Example call
let original = [{
key1: 1,
key2: 2,
array: [{
thisId: "xxxxx",
thisValue: 3,
}, {
notThisId: "yyyy",
notThisValue: 4,
}],
key3: 5
}, {
key1: 6,
key2: 7,
array: [{
anotherId: "zzzzz",
anotherValue: 8
}],
key3: 9
}];
let editedPostId = "xxxxx";
let editedContent = 42;
console.log(setDeep(original, editedPostId, editedContent));
請注意,您為非嵌套結構提供的代碼似乎創建了一個新數組,但它仍然會改變原始數組。當您希望原件保持原樣時,您必須小心地對受影響的部分進行深度複製。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句