![](/img/trans.png)
[英]How to change values in nested object to concat with array, and matching with id with javascript
[英]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 的評論很有啟發性,所以我希望他們不介意我在這里展開討論。
將對象變成字符串。
再次將其解析回一個對象。
我不知道的是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.