![](/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.