Tre*_*vor -2 javascript arrays recursion
我正在构建一个需要重命名某些属性键的递归“按摩”函数。我一直在尝试一些递归方法,但到目前为止都无济于事。
例如,我需要从这个深度嵌套对象内的所有数组中删除“数组”一词。
样本输入:
var input = {
test: {
testArray1: [
{
testArray2: [
{
sample: {
testArray3: [],
},
},
],
},
],
},
};
Run Code Online (Sandbox Code Playgroud)
预期输出:
var output = {
test: {
test1: [
{
test2: [
{
sample: {
test3: [],
},
},
],
},
],
},
};
Run Code Online (Sandbox Code Playgroud)
最好的方法(没有递归)可以将JSONto转换为stringwith JSON.stringify(),对 进行一些replace()操作string,然后将其转换回JSONwith JSON.parse(),如下所示:
const input = {
test: {testArray1: [
{testArray2: [
{sample: {testArray3: ["Array"],},},
],},
],},
};
let res = JSON.stringify(input).replace(/(Array)([^:]*):/g, "$2:");
res = JSON.parse(res);
console.log(res);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |