简体   繁体   English

如何更改此嵌套对象数组中每个 id 的值?

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

I have data structure similar like this我有类似这样的数据结构

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

I would like to change every id to null .我想将每个id更改为null

I know I could do loops and manually assign null to id .我知道我可以做循环并手动将null分配给id Is there any easy way to do this in JavaScript?有没有什么简单的方法可以在 JavaScript 中做到这一点?

Bravo's comment was illuminating so I hope they don't mind if I expand on it here. Bravo 的评论很有启发性,所以我希望他们不介意我在这里展开讨论。

  1. Turn the object into a string.将对象变成字符串。

  2. Parse it back into an object again.再次将其解析回一个对象。

What I didn't know is that JSON.parse has a "reviver" function that allows you to transform the string value as it's being parsed.我不知道的是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);

Without changing the object to a JSON string, you could use recursion:在不将对象更改为 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);

This mutates the given object in place.这会在适当的位置改变给定的对象。

For fun: the same function as a one-liner:为了好玩:与单行相同的功能:

 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