gpt4 book ai didi

javascript - 解决来自 JSON 对象的循环引用

转载 作者:可可西里 更新时间:2023-11-01 01:55:16 26 4
gpt4 key购买 nike

如果我有一个来自 json.net 的序列化 JSON,如下所示:

User:{id:1,{Foo{id:1,prop:1}},
FooList{$ref: "1",Foo{id:2,prop:13}}

我想在 FooList 上有一个 foreach 的 knockout 输出,但我不确定如何继续,因为 $ref 东西可能会抛出东西。

我认为解决方案是以某种方式强制所有 Foos 在 FooList 中呈现,而不是使用:

PreserveReferencesHandling = PreserveReferencesHandling.Objects

但这似乎很浪费..

最佳答案

我发现了一些错误并实现了数组支持:

function resolveReferences(json) {
if (typeof json === 'string')
json = JSON.parse(json);

var byid = {}, // all objects by id
refs = []; // references to objects that could not be resolved
json = (function recurse(obj, prop, parent) {
if (typeof obj !== 'object' || !obj) // a primitive value
return obj;
if (Object.prototype.toString.call(obj) === '[object Array]') {
for (var i = 0; i < obj.length; i++)
// check also if the array element is not a primitive value
if (typeof obj[i] !== 'object' || !obj[i]) // a primitive value
continue;
else if ("$ref" in obj[i])
obj[i] = recurse(obj[i], i, obj);
else
obj[i] = recurse(obj[i], prop, obj);
return obj;
}
if ("$ref" in obj) { // a reference
var ref = obj.$ref;
if (ref in byid)
return byid[ref];
// else we have to make it lazy:
refs.push([parent, prop, ref]);
return;
} else if ("$id" in obj) {
var id = obj.$id;
delete obj.$id;
if ("$values" in obj) // an array
obj = obj.$values.map(recurse);
else // a plain object
for (var prop in obj)
obj[prop] = recurse(obj[prop], prop, obj);
byid[id] = obj;
}
return obj;
})(json); // run it!

for (var i = 0; i < refs.length; i++) { // resolve previously unknown references
var ref = refs[i];
ref[0][ref[1]] = byid[ref[2]];
// Notice that this throws if you put in a reference at top-level
}
return json;
}

关于javascript - 解决来自 JSON 对象的循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15312529/

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