簡體   English   中英

如何更改此嵌套對象數組中每個 id 的值?

[英]How to change values of every id in this nested object array?

我有類似這樣的數據結構

{"id": 1, "a": [{"id": 2, "b": [{"id": 3, "c": [{"id": 4}]}]}]}

我想將每個id更改為null

我知道我可以做循環並手動將null分配給id 有沒有什么簡單的方法可以在 JavaScript 中做到這一點?

Bravo 的評論很有啟發性,所以我希望他們不介意我在這里展開討論。

  1. 將對象變成字符串。

  2. 再次將其解析回一個對象。

我不知道的是JSON.parse一個“reviver”函數,它允許您在解析字符串值時對其進行轉換。

 const data = {"id": 1, "a": [{"id": 2, "b": [{"id": 3, "c": [{"id": 4}]}]}]}; // Turn the data into a string const str = JSON.stringify(data); // Parse the string back to an object // but using the reviver function to turn the value of any id // keys to null const newObj = JSON.parse(str, (key, value) => key === 'id' ? null : value); console.log(newObj);

在不將對象更改為 JSON 字符串的情況下,您可以使用遞歸:

 function clearIds(obj) { if ("id" in Object(obj)) obj.id = null; Object.values(Object(obj)).forEach(clearIds); } // Demo let obj = {"id": 1, "a": [{"id": 2, "b": [{"id": 3, "c": [{"id": 4}]}]}]}; clearIds(obj); console.log(obj);

這會在適當的位置改變給定的對象。

為了好玩:與單行相同的功能:

 const clearIds = o => "id" in Object(o) && (o.id = null) || Object.values(Object(o)).forEach(clearIds); // Demo let obj = {"id": 1, "a": [{"id": 2, "b": [{"id": 3, "c": [{"id": 4}]}]}]}; clearIds(obj); console.log(obj);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM