如何将嵌套对象结构化为对象数组?

huangapple go评论68阅读模式
英文:

How to structure nested objects into an array of objects?

问题

我有这个JSON结构-

let data = {
  "Branches": {
    "Marketing": {
      "Sub-Branches": {
        "Digital Marketing": {
          "Sub-Branches": {
            "Search Engine Optimization": null,
            "Social Media Marketing": null
          }
        },
        "Traditional Marketing": {
          "Sub-Branches": {
            "Print Advertising": null,
            "Broadcast Advertising": null
          }
        }
      }
    },
    "Finance": {
      "Sub-Branches": {
        "Investment Banking": {
          "Sub-Branches": {
            "Equity Research": null,
            "Mergers & Acquisitions": null
          }
        },
        "Corporate Finance": {
          "Sub-Branches": {
            "Financial Modeling": null,
            "Risk Management": null
          }
        }
      }
    }
  }
};

我想将其转换为这种格式-

[{
    id: 1677230955479,
    name: "Marketing",
    children: [{
        id: 1677230955479,
        name: "Digital Marketing",
        children: [{
            id: 1677230955479,
            name: "Search Engine Optimization",
            children: [],
          },
          {
            id: 1677230955479,
            name: "Social Media Marketing",
            children: [],
          },
        ],
      },
      {
        id: 1677230955479,
        name: "Traditional Marketing",
        children: [{
            id: 1677230955479,
            name: "Print Advertising",
            children: [],
          },
          {
            id: 1677230955479,
            name: "Broadcast Advertising",
            children: [],
          },
        ],
      },
    ],
  },
  {
    id: 1677230955479,
    name: "Finance",
    children: [{
        id: 1677230955479,
        name: "Investment Banking",
        children: [{
            id: 1677230955479,
            name: "Equity Research",
            children: [],
          },
          {
            id: 1677230955479,
            name: "Mergers & Acquisitions",
            children: [],
          },
        ],
      },
      {
        id: 1677230955479,
        name: "Corporate Finance",
        children: [{
            id: 1677230955479,
            name: "Financial Modeling",
            children: [],
          },
          {
            id: 1677230955479,
            name: "Risk Management",
            children: [],
          },
        ],
      },
    ],
  },
];

我尝试了这个方法-

let data = {
  "Branches": {
    "Marketing": {
      "Sub-Branches": {
        "Digital Marketing": {
          "Sub-Branches": {
            "Search Engine Optimization": null,
            "Social Media Marketing": null
          }
        },
        "Traditional Marketing": {
          "Sub-Branches": {
            "Print Advertising": null,
            "Broadcast Advertising": null
          }
        }
      }
    },
    "Finance": {
      "Sub-Branches": {
        "Investment Banking": {
          "Sub-Branches": {
            "Equity Research": null,
            "Mergers & Acquisitions": null
          }
        },
        "Corporate Finance": {
          "Sub-Branches": {
            "Financial Modeling": null,
            "Risk Management": null
          }
        }
      }
    }
  }
}

let result = [];

function iterate(obj) {
  let children = [];
  if (obj) {
    for (const [key, value] of Object.entries(obj)) {
      children.push({
        id: Date.now(),
        name: key,
        children: value ? iterate(value["Sub-Branches"]) : []
      })
    }
  }
  return children;
}

// 从这里开始
for (const [key, value] of Object.entries(data.Branches)) {
  let obj = {};
  obj.id = Date.now();
  obj.name = key
  obj.children = iterate(value["Sub-Branches"]);
  result.push(obj)
}

console.log(result)

有什么建议吗?

英文:

I have this JSON structure-

let data = {
"Branches": {
"Marketing": {
"Sub-Branches": {
"Digital Marketing": {
"Sub-Branches": {
"Search Engine Optimization": null,
"Social Media Marketing": null
}
},
"Traditional Marketing": {
"Sub-Branches": {
"Print Advertising": null,
"Broadcast Advertising": null
}
}
}
},
"Finance": {
"Sub-Branches": {
"Investment Banking": {
"Sub-Branches": {
"Equity Research": null,
"Mergers & Acquisitions": null
}
},
"Corporate Finance": {
"Sub-Branches": {
"Financial Modeling": null,
"Risk Management": null
}
}
}
}
}
};

I want to convert that into this format-

[{
id: 1677230955479,
name: "Marketing",
children: [{
id: 1677230955479,
name: "Digital Marketing",
children: [{
id: 1677230955479,
name: "Search Engine Optimization",
children: [],
},
{
id: 1677230955479,
name: "Social Media Marketing",
children: [],
},
],
},
{
id: 1677230955479,
name: "Traditional Marketing",
children: [{
id: 1677230955479,
name: "Print Advertising",
children: [],
},
{
id: 1677230955479,
name: "Broadcast Advertising",
children: [],
},
],
},
],
},
{
id: 1677230955479,
name: "Finance",
children: [{
id: 1677230955479,
name: "Investment Banking",
children: [{
id: 1677230955479,
name: "Equity Research",
children: [],
},
{
id: 1677230955479,
name: "Mergers & Acquisitions",
children: [],
},
],
},
{
id: 1677230955479,
name: "Corporate Finance",
children: [{
id: 1677230955479,
name: "Financial Modeling",
children: [],
},
{
id: 1677230955479,
name: "Risk Management",
children: [],
},
],
},
],
},
];

I am trying this approach-

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let data = {
&quot;Branches&quot;: {
&quot;Marketing&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Digital Marketing&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Search Engine Optimization&quot;: null,
&quot;Social Media Marketing&quot;: null
}
},
&quot;Traditional Marketing&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Print Advertising&quot;: null,
&quot;Broadcast Advertising&quot;: null
}
}
}
},
&quot;Finance&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Investment Banking&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Equity Research&quot;: null,
&quot;Mergers &amp; Acquisitions&quot;: null
}
},
&quot;Corporate Finance&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Financial Modeling&quot;: null,
&quot;Risk Management&quot;: null
}
}
}
}
}
}
let result = [];
function iterate(obj) {
let children = [];
if (obj) {
for (const [key, value] of Object.entries(obj)) {
children.push({
id: Date.now(),
name: key,
children: value ? iterate(value[&quot;Sub-Branches&quot;]) : []
})
}
}
return children;
}
// Start From Here
for (const [key, value] of Object.entries(data.Branches)) {
let obj = {};
obj.id = Date.now();
obj.name = key
obj.children = iterate(value[&quot;Sub-Branches&quot;]);
result.push(obj)
}
console.log(result)

<!-- end snippet -->

Any suggestions?

答案1

得分: 2

你可以通过递归的方式查看对象的值。

英文:

You could take a recursive approach by looking to the values of the objects.

<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const
getItems = object => Object
.entries(object)
.map(([name, value]) => ({
id: Date.now(),
name,
...(value ? { children: getItems(value["Sub-Branches"]) } : {})
})),
data = { Branches: { Marketing: { "Sub-Branches": { "Digital Marketing": { "Sub-Branches": { "Search Engine Optimization": null, "Social Media Marketing": null } }, "Traditional Marketing": { "Sub-Branches": { "Print Advertising": null, "Broadcast Advertising": null } } } }, Finance: { "Sub-Branches": { "Investment Banking": { "Sub-Branches": { "Equity Research": null, "Mergers & Acquisitions": null } }, "Corporate Finance": { "Sub-Branches": { "Financial Modeling": null, "Risk Management": null } } } } } },
result = getItems(data.Branches);

console.log(result);

<!-- language: lang-css -->
.as-console-wrapper { max-height: 100% !important; top: 0; }
<!-- end snippet -->

答案2

得分: 0

输入和期望的输出都包含相同类型的结构,唯一的区别是您希望根据父子关系将嵌套对象转换为对象数组。如果是这样,您可以通过迭代data对象,然后使用递归函数动态创建对象数组(子对象)来实现这一目标。

演示示例 :

// 输入数据
let data = {
  "Branches": {
    "Marketing": {
      "Sub-Branches": {
        "Digital Marketing": {
          "Sub-Branches": {
            "Search Engine Optimization": null,
            "Social Media Marketing": null
          }
        },
        "Traditional Marketing": {
          "Sub-Branches": {
            "Print Advertising": null,
            "Broadcast Advertising": null
          }
        }
      }
    },
    "Finance": {
      "Sub-Branches": {
        "Investment Banking": {
          "Sub-Branches": {
            "Equity Research": null,
            "Mergers & Acquisitions": null
          }
        },
        "Corporate Finance": {
          "Sub-Branches": {
            "Financial Modeling": null,
            "Risk Management": null
          }
        }
      }
    }
  }
};

// 输出将存储在此变量中。
const arr = [];

// 我们将递归调用以为每个父对象绑定嵌套的“children”的方法。
function getChildren(obj) {
  const innerArr = [];
  if (Object.hasOwn(obj, 'Sub-Branches')) {
    Object.keys(obj['Sub-Branches']).forEach(subBranch => {
      innerArr.push({
        name: subBranch,
        children: obj['Sub-Branches'][subBranch] ? getChildren(obj['Sub-Branches'][subBranch]) : []
      })
    })
  }
  return innerArr;
}

// 遍历输入数组并调用“getChildren”方法以绑定嵌套的子对象。
Object.keys(data.Branches).forEach((key, index) => {
  arr.push({
    name: key,
    id: index + 1,
    children: getChildren(data.Branches[key])
  })
})

// 输出
console.log(arr);

请注意,这是一段JavaScript代码,用于将嵌套结构转换为数组对象,基于父子关系。

英文:

Both input and expected output is containing same type of structure, The only thing is that you want to convert the nested objects into an array of objects based on the parent child relationship. If Yes, You can achieve this by iterating the data object and then create an array of objects (children) dynamically with the help of recursive function.

Live Demo :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// Input data
let data = {
&quot;Branches&quot;: {
&quot;Marketing&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Digital Marketing&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Search Engine Optimization&quot;: null,
&quot;Social Media Marketing&quot;: null
}
},
&quot;Traditional Marketing&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Print Advertising&quot;: null,
&quot;Broadcast Advertising&quot;: null
}
}
}
},
&quot;Finance&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Investment Banking&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Equity Research&quot;: null,
&quot;Mergers &amp; Acquisitions&quot;: null
}
},
&quot;Corporate Finance&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Financial Modeling&quot;: null,
&quot;Risk Management&quot;: null
}
}
}
}
}
};
// Output will get store in this variable.
const arr = [];
// function which we will call recursively to bind the nested &#39;children&#39; for each parent.
function getChildren(obj) {
const innerArr = [];
if (Object.hasOwn(obj, &#39;Sub-Branches&#39;)) {
Object.keys(obj[&#39;Sub-Branches&#39;]).forEach(subBranch =&gt; {
innerArr.push({
name: subBranch,
children: obj[&#39;Sub-Branches&#39;][subBranch] ? getChildren(obj[&#39;Sub-Branches&#39;][subBranch]) : []
})
})
}
return innerArr;
}
// Iterate the input array and invoke &#39;getChildren&#39; method to bind nested children.
Object.keys(data.Branches).forEach((key, index) =&gt; {
arr.push({
name: key,
id: index + 1,
children: getChildren(data.Branches[key])
})
})
// Output
console.log(arr);

<!-- end snippet -->

答案3

得分: 0

以下是代码的中文翻译部分:

// 使用以下代码来组织你的数据。

let data = {
  "分支": {
    "市场营销": {
      "子分支": {
        "数字营销": {
          "子分支": {
            "搜索引擎优化": null,
            "社交媒体营销": null
          }
        },
        "传统营销": {
          "子分支": {
            "印刷广告": null,
            "广播广告": null
          }
        }
      }
    },
    "金融": {
      "子分支": {
        "投资银行": {
          "子分支": {
            "股权研究": null,
            "并购": null
          }
        },
        "公司金融": {
          "子分支": {
            "财务建模": null,
            "风险管理": null
          }
        }
      }
    }
  }
};

function 转换对象为数组(obj) {
  function 遍历(node) {
    return Object.keys(node).map(key => {
      const 子节点 = node[key];
      return {
        名称: key,
        子项: 子节点 && typeof 子节点 === 'object' ? 遍历(子节点) : []
      };
    });
  }
  
  return 遍历(obj)[0].子项;
}

console.log(转换对象为数组(data))

请注意,我只翻译了代码部分,没有包括评论或其他内容。

英文:

You can use the following code to structure your data.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let data = {
&quot;Branches&quot;: {
&quot;Marketing&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Digital Marketing&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Search Engine Optimization&quot;: null,
&quot;Social Media Marketing&quot;: null
}
},
&quot;Traditional Marketing&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Print Advertising&quot;: null,
&quot;Broadcast Advertising&quot;: null
}
}
}
},
&quot;Finance&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Investment Banking&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Equity Research&quot;: null,
&quot;Mergers &amp; Acquisitions&quot;: null
}
},
&quot;Corporate Finance&quot;: {
&quot;Sub-Branches&quot;: {
&quot;Financial Modeling&quot;: null,
&quot;Risk Management&quot;: null
}
}
}
}
}
};
function convertObjectToArray(obj) {
function traverse(node) {
return Object.keys(node).map(key =&gt; {
const child = node[key];
return {
name: key,
children: child &amp;&amp; typeof child === &#39;object&#39; ? traverse(child) : []
};
});
}
return traverse(obj)[0].children;
}
console.log(convertObjectToArray(data))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月24日 17:38:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定