【问题标题】:AngularJS / javascript - flatten unique values object into SIMPLE listAngularJS / javascript - 将唯一值对象展平为简单列表
【发布时间】:2019-02-10 11:13:54
【问题描述】:

我有一个动态生成的、多级嵌套的唯一值对象。我想将它展平(使用 AngularJS 或 vanilla JS)并为每个键/值创建一个简单的数组或对象。所以如果对象看起来像这样:

[ 

{name : "parent",
 age: 21,
 children: [
     { name : "child",
     dob: [{
         day: "01",
         month: "01",
         year : "82"
     }],
     children: [
     { 
        name : "grandchild",
        dob: [{
            day: "01",
            month: "01",
            year : "02"
            }]
      }
    ]
   }
 ]
}

];

展平的对象应该是这样的:

"name":"parent",
"age":21,
"children.name":"child",
"children.dob.day":"01",
"children.dob.month":"01",
"children.dob.year":"82",
"children.children.name":"grandchild",
"children.children.dob.day":"01",
"children.children.dob.month":"01",
"children.children.dob.year":"02"

我找到了 2 个函数来展平对象,但都在每个节点旁边插入索引。 (0.children.0.children.0.dob.0.year) 这对我没有用,也没有必要,因为我的价值观是独一无二的。我需要上面的格式。您可以在此 codepen 中看到我当前使用的功能: https://codepen.io/anon/pen/qMXEmB

谁能帮我从我的最终对象中删除那些讨厌的“零”?

【问题讨论】:

    标签: javascript arrays angularjs json flatten


    【解决方案1】:

    残酷,但不是

    toReturn[i + '.' + x] = flatObject[x];
    

    您可以像这样删除 0:

    let index = i === "0" ? '' : i + '.';
    toReturn[index + x] = flatObject[x];
    

    【讨论】:

      猜你喜欢
      • 2017-09-13
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2017-05-22
      • 2022-07-21
      • 1970-01-01
      相关资源
      最近更新 更多