javascript - 根据特定键将对象数组转换为深层嵌套对象

标签 javascript arrays json recursion javascript-objects

我有一个对象数组。

{
  c1 : ["a1", "c2"],
  c2 : ["b1"],
  c3: ["d1"], 
  b1: ["e"]
  d1: ["k"]
}

我需要将对象按层次结构排列。像这样,

{ 
   c1: [{a1: null}, {
           c2: [{ 
              b1: "e"
           }]
       }],
   c3: [{ d1: "k" }]
}

请注意,我们可以省略last (deepest) key: value pair 中的数组。到目前为止,这是我尝试过的。

for (v in hash){ 
   hash[v].forEach(function(ar){
    if(hash[ar]){
        if (new_hash[v] == undefined){
            new_hash[v] = []
        }
        new_hash[v].push({[ar] : hash[ar]})
    }
   })
}

我认为这个问题需要动态规划(保存状态的递归),我不擅长。请帮忙。

最佳答案

您可以使用另一个哈希表并在其中存储所有节点之间的关系,并从中取出没有父节点的结果节点。

为了克服节点没有 child 的问题,我添加了一个空数组,因为原来想要的结构要么有null,要么根本没有 child ,就像这个节点

{ b1: "e" }

它应该在空标记的位置

{ b1: [{ e: null }] }

此解决方案的特点是一个空数组,可以用任何其他值替换。

{ b1: [{ e: [] }] }

var hash = { c1: ["a1", "c2"], c2: ["b1"], c3: ["d1"], b1: ["e"], d1: ["k"] },
    keys = Object.keys(hash),
    parents = new Set(keys),
    temp = {},
    tree ;

keys.forEach(k => hash[k].forEach(t => {
    parents.delete(t);
    temp[k] = temp[k] || [];
    temp[t] = temp[t] || [];
    if (!temp[k].some(o => t in o)) temp[k].push({ [t]: temp[t] });
}));

tree = Object.assign({}, ...Array.from(parents, k => ({ [k]: temp[k] })));

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

关于javascript - 根据特定键将对象数组转换为深层嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55999798/

相关文章:

javascript - setTimeout/clearTimeout 问题,似乎没有重置

javascript - 将跨度附加到页面上的特定跨度

javascript - 如何更新 AngularJS 中多个 Controller 共享服务属性的异步模型更改的绑定(bind)?

asp.net - 如何使用 javascript 获取 ASP.NET 的文本框控件的值

c - 为什么我不能初始化我的数组?

c++ - 如何在类中声明/实现某种类型的数组(C++)

json - 如何使用 NSURLSession 在 Swift 中解析 JSON

java - 如何更改 txt 文件中的数据(字符串)以便我可以对该数据进行数学运算?

c++ - 如何将 std::string 格式的 JSON 解码为 Boost 属性树?

java - 使用 Gson 创建特定的 JSON 字符串