gpt4 book ai didi

javascript - JSON.Stringify 方法替换参数不适用于嵌套对象

转载 作者:数据小太阳 更新时间:2023-10-29 05:17:23 25 4
gpt4 key购买 nike

我有一个对象,我想将这个对象的简化版本发送到服务器。

{
"fullName": "Don Corleone",
"actor": {
"actorId": 2,
"name": "Marlon",
"surname": "Brando",
"description": "Marlon Brando is widely considered the greatest movie actor of all time... ",
"heroList": [],
"photo": "C:\\projects\\files\\actor\\1532955376934.png"
},
"heroProfilePhoto": "data:image/png;base64,/9j/...
"production": {
"title": "The Godfather",
"imdbRate": 9.2,
"genre": "8",
"releaseDate": "1972-03-23T21:00:00.000Z",
"director": "Francis Ford Coppola",
"writer": "Mari Puzo",
"detail": "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son."
}
}"

我有两个问题::

1) 是否可以使用 replacer parameter 提取类似的内容?的 JSON.stringify()

 {
"fullName": "Don Corleone",
"actor": {
"actorId": 2
}
}"

2) 至少我可以用 replacer parameter 提取这样的东西的 JSON.stringify()

{
"fullName": "Don Corleone",
"actor": {
"actorId": 2,
"name": "Marlon",
"surname": "Brando",
"description": "Marlon Brando is widely considered the greatest movie actor of all time... ",
"heroList": [],
"photo": "C:\\projects\\files\\actor\\1532955376934.png"
},
}"

当我这样使用时没问题:

JSON.stringify(hero, ['fullName']) 结果 -> "{"fullName":"Don Corleone"}"

但是这个:

JSON.stringify(hero, ['fullName', 'actor']) 结果 -> "{"fullName":"Don Corleone","actor":{}} "

为什么actor属性为空?

最佳答案

JSON.stringify 要求您传入所有您希望返回的数据。 'actor' 本身是不够的。

你想要:

JSON.stringify(hero, ['fullName', 'actor', 'actorId'])

编辑

所以我做了一些测试,我很好奇如果 actorId 也存在于父对象中会发生什么,并且结果在。

如果 actorId 存在于 actor 对象内部,并且在父对象。如果您不希望出现这种情况,则必须根据需要创建一个更复杂的函数并将其传递给 JSON.stringify(),如文档中所述 here

这里有一些例子:

var json = {
key1: "Value for key1 in parent",
key2: {
key3: "Value for key3 in child",
key4: "Value for key4 in child"
},
key4: "Value for key4 in parent"
}

var out1 = JSON.stringify(json, ['key1', 'key3'])
/*
out1 = {
key1: "Value for key1 in parent"
} // No key3!
*/


var out2 = JSON.stringify(json, ['key1', 'key2', 'key3'])
/*
out2 = {
key1: "Value for key1 in parent",
key2: {
key3: "Value for key3 in child"
}
}
*/

var out3 = JSON.stringify(json, ['key1', 'key2', 'key3', 'key4'])
/*
out3 = {
key1: "Value for key1 in parent",
key2: {
key3: "Value for key3 in child",
key4: "Value for key4 in child" // Both key4 returned
},
key4: "Value for key4 in parent" // Both key4 returned
}
*/

关于javascript - JSON.Stringify 方法替换参数不适用于嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51672378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com