gpt4 book ai didi

javascript - 如果在 JavaScript 中它是空对象,如何将最深对象更改为字符串值

转载 作者:行者123 更新时间:2023-11-29 11:02:57 25 4
gpt4 key购买 nike

假设我有这个对象:

{CONN_INFO: {CFGSwitch: {412: {}}}}

它的深度为 4。我想将键 412 重新分配给 "{}",这样最终的对象将是

{CONN_INFO: {CFGSwitch: {412: "{}"}}}

检查深度的函数:

function checkDepth(object) {
var level = 1;
var key;
for(key in object) {
if (!object.hasOwnProperty(key)) continue;

if(typeof object[key] == 'object'){
var depth = checkDepth(object[key]) + 1;
level = Math.max(depth, level);
}
}
return level;
}

我有这样的东西,但我不确定它是否是最佳的或者是否适用于所有情况。将不胜感激。

function checkIfLastLevelEmpty(obj, depth) {
for (var key in obj) {
var val = obj[key];
if (Object.keys(obj[key]).length === 0) {
obj[key] = "{}";
}
else {
if (depth >0) {
checkIfLastLevelEmpty(val, depth-1);
}
}
}
}

最佳答案

首先让我们结合一些知识:

How do I test for an empty JavaScript object?

上面的问题有一个很棒的答案,里面有很多选项,我将编辑片段以形成几个函数:

function isObject (obj) {
return obj.constructor === Object;
}

function isEmptyObject (obj) {
return Object.keys(obj).length === 0 && isObject(obj);
}

王牌。现在,假设你有一个非常线性的对象结构,它不是一个复杂的数组并且不关心深度(只关心它是空的)让一个函数在树中循环。

function convertEmptyObjects (obj, currentDepth) {
currentDepth = currentDepth || 0;
for (var key in obj) {
var val = obj[key];
if (isObject(val)) {
if (isEmptyObject(val)) {
obj[key] = "{}";
console.log("Defeated boss ("+ key +") on level "+ currentDepth +"!");
}else{
convertDeepestEmptyObject (val, currentDepth + 1);
}
}
}
return obj;
}

让我们在一个看起来很糟糕的对象上测试一下:

var testObject = {
CONN_INFO: {
CFGSwitch: {
412: {}, // Level 2
413: {
content: {} // Level 3
}
},
DummySwitch: {} // Level 1
},
TEST_CONN_INFO: {
CFGSwitch: {
414: {}, // Level 2
415: {
content: {
host: "google",
port: "8080",
protocol: {} // Level 4
}
}
}
},
STAGING_CONN_INFO: {} // Level 0
}

convertEmptyObjects(testObject);
JSON.stringify(testObject)

/* Output:
* Defeated boss (412) on level 2!
* Defeated boss (content) on level 3!
* Defeated boss (DummySwitch) on level 1!
* Defeated boss (414) on level 2!
* Defeated boss (protocol) on level 4!
* Defeated boss (STAGING_CONN_INFO) on level 0!
*/

// Result:
{
"CONN_INFO": {
"CFGSwitch": {
"412": "{}", // Empty String {}
"413": {
"content": "{}" // Empty String {}
}
},
"DummySwitch": "{}" // Empty String {}
},
"TEST_CONN_INFO": {
"CFGSwitch": {
"414": "{}", // Empty String {}
"415": {
"content": {
"host": "google",
"port": "8080",
"protocol": "{}" // Empty String {}
}
}
}
},
"STAGING_CONN_INFO": "{}" // Empty String {}
}

给你。

关于javascript - 如果在 JavaScript 中它是空对象,如何将最深对象更改为字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43850795/

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