英文:
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 = {
"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;
}
// 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["Sub-Branches"]);
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 = {
"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
}
}
}
}
}
};
// Output will get store in this variable.
const arr = [];
// function which we will call recursively to bind the nested 'children' for each parent.
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;
}
// Iterate the input array and invoke 'getChildren' method to bind nested children.
Object.keys(data.Branches).forEach((key, index) => {
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 = {
"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
}
}
}
}
}
};
function convertObjectToArray(obj) {
function traverse(node) {
return Object.keys(node).map(key => {
const child = node[key];
return {
name: key,
children: child && typeof child === 'object' ? traverse(child) : []
};
});
}
return traverse(obj)[0].children;
}
console.log(convertObjectToArray(data))
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论