将具有父子关系的对象数组转换为嵌套对象。

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

Convert array of objects with parent child relations to nested object

问题

以下是您提供的代码的翻译结果:

{
  "A1": {
    "B1": {
      "C11": {
        "D100": ["E1000", "E1100"],
        "D111": [],
        "D112": [],
        "D113": [],
        "D131": []
      },
      "C12": [],
      "C13": []
    }
  }
}

这是将提供的数组转换为嵌套对象以表示关系的目标对象。

英文:

Lets say I have the following array of objects which have parent child relations:

[
  { A1: [ "B1" ] },
  { B1: [ "C11", "C12", "C13" ] },
  { C11: [ "D100", "D111", "D112", "D113", "D131" ] },
  { D100: [ "E1000", "E1100" ] }
]

How can I convert the above array to a nested object to represent the relations?
So the target object would be:

{
A1: 
{
    B1:
    {
        C11: 
        {
            D100: ["E1000", "E1100"],
            D111: [],
            D112: [],
            D113: [],
            D131: []
        },
        C12: [],
        C13: []
    }
}

}

I tried several recursive approaches with reduce etc. but still struggle to get all levels converted correctly.

答案1

得分: 1

以下是翻译好的部分:

假设有一个具有相同模式的对象,您可以使用对嵌套对象的引用来获取不同的值,如数组而不是对象。您可以在输入数据中指定这一点。

const data = [{ A1: ["B1"] }, { B1: ["C11", "C12", "C13"] }, { C11: ["D100", "D111", "D112", "D113", "D131"] }, { D100: ["E1000", "E1100"] }];
const result = data.reduce((r, o) => {
    Object.entries(o).forEach(([k, a]) => a.forEach(l => (r[k] || r._)[l] ??= r[l] = {}));
    return r;
}, { _: {} });

console.log(result._);
.as-console-wrapper { max-height: 100% !important; top: 0; }

希望这对您有所帮助。

英文:

Assuming an object with same pattern, you could takean object with references to the neste objects.

If you like to get different values, like arrays instead of objects, you could specify this in the inout data.

<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const
data = [{ A1: ["B1"] }, { B1: ["C11", "C12", "C13"] }, { C11: ["D100", "D111", "D112", "D113", "D131"] }, { D100: ["E1000", "E1100"] }],
result = data.reduce((r, o) => {
Object
.entries(o)
.forEach(([k, a]) => a.forEach(l => (r[k] || r._)[l] ??= r[l] = {}));
return r;
}, { _: {} });

console.log(result._);

<!-- language: lang-css -->

.as-console-wrapper { max-height: 100% !important; top: 0; }

<!-- end snippet -->

答案2

得分: 1

以下是代码部分的翻译:

您可以使用递归来实现所需的结果也许我的示例有点笨拙但它可以实现

// 开始代码片段: js 隐藏: false 控制台: true babel: false

// 语言: lang-js

const array = [
  { A1: ["B1"] },
  { B1: ["C11", "C12", "C13"] },
  { C11: ["D100", "D111", "D112", "D113", "D131"] },
  { D100: ["E1000", "E1100"] }
]

// 构建对象的结构

const result = array.reduce((prev, current) => {
  Object.entries(current).map(([key, value]) => {
    if (value) {
      prev[key] = {};
      value.map(el => prev[key][el] = {});
    }
  });
  return prev;
})

// 循环并表示关系

Object.values(result).map(value => {
  if (Object.keys(value).length) {
    represent(value, result);
  }
})

function represent(value, obj) {
  Object.keys(value).map(key => {
    if (obj[key]) {
      value[key] = { ...obj[key] };
      delete(obj[key]);
      represent(value[key], obj);
    }
  })
}

// 转换并将空对象关联到数组

associate(result);

function associate(obj) {
  Object.entries(obj).map(([key, value]) => {
    const values = Object.values(value).filter(o => Object.keys(o).length);
    if (values.length) {
      associate(value)
    } else {
      if (Object.keys(value).length === 1) {
        obj[key] = [];
      } else {
        obj[key] = Object.keys(value);
      }
    }
  });
}

console.log(JSON.stringify(result, null, 2));

// 结束代码片段

希望这有帮助。如果您需要更多信息,请随时告诉我。

英文:

You can achieve the desired result using recursion. Maybe my example is a bit clunky, but it does the trick:

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

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

const array = [
{ A1: [ &quot;B1&quot; ] },
{ B1: [ &quot;C11&quot;, &quot;C12&quot;, &quot;C13&quot; ] },
{ C11: [ &quot;D100&quot;, &quot;D111&quot;, &quot;D112&quot;, &quot;D113&quot;, &quot;D131&quot; ] },
{ D100: [ &quot;E1000&quot;, &quot;E1100&quot; ] }
]
// building a structure of objects
const result = array.reduce((prev, current) =&gt; {
Object.entries(current).map(([key, value]) =&gt; {
if (value) {
prev[key] = {};
value.map(el =&gt; prev[key][el] = {});
}
});
return prev;
}, {})
// loop and represent relations
Object.values(result).map(value =&gt; {
if (Object.keys(value).length) {
represent(value, result);
}
})
function represent(value, obj) {
Object.keys(value).map(key =&gt; {
if (obj[key]) {
value[key] = { ...obj[key] };
delete(obj[key]);
represent(value[key], obj);
}
})
}
// convert and associate empty objects to array
associate(result);
function associate(obj) {
Object.entries(obj).map(([key, value]) =&gt; {
const values = Object.values(value).filter(o =&gt; Object.keys(o).length);
if(values.length){
associate(value)
}else{
if(Object.keys(value).length === 1) {
obj[key] = [];
}else {
obj[key] = Object.keys(value);
}
}
});
}
console.log(JSON.stringify(result, null, 2));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月6日 22:38:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950792.html
匿名

发表评论

匿名网友

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

确定