好的。
我有一个 JSON 对象,其中对象的每个项目都是顶级对象...没有嵌套关系。有些项目是嵌套的,但一切都是顶级的。
嵌套关系的设置方式是通过 ID 值。
- 项目 a = item_a
- 与 a = item_a.item_b 相关的项目 b
- 项目 c = item_c
- 与 c 相关的项目 d = item_c.item_d
- 与 d 相关的项目 e = item_c.item_d.item_e
我尝试过拆分 .
并循环遍历整个 json 对象并对它们进行排序。我已经尝试了 4 或 5 种我能想到的不同方法,但都无法正常工作。
我想要最终得到的是一个看起来像这样的单个对象。
Obj = [{
item_a: {
nestedItems: [{
item_b: {}
}]
},
item_c: {
nestedItems: [{
item_d: {
nestedItems: {
item_e: {}
}
}
}]
}
}];
我无法更改输出,所以我们不要问这个问题。这就是我要解决的问题。谁能帮助我了解排序的最佳方法?
这是我目前的状态...但还远未完成:
function getNestedAttributes(attrs) // attrs is the JSON object
{
var nested = [];
for ( var i=0; i<attrs.length; i++ )
{
var idLevels = splitId(attrs[i].id); // split on . return array
if ( idLevels.length == 1 )
{
nested[idLevels[0]] = attrs[i];
nested[idLevels[0]]['nestedAttributes'] = [];
}
if ( idLevels.length > 1 )
{
nested[idLevels[0]]['nestedAttributes'].push(attrs[i]);
}
}
console.log(nested);
}
以上内容在一定程度上是有效的。我将所有内容都设置为数组,这很好,但它仅适用于具有一级嵌套的对象。有些项目最多可以嵌套 4 层。
必须有更好的方法在 JS 中循环它。
JSON:
attributes: [
{
id: "item_a",
name: "Item A Name",
...
},
{
id: "item_a.item_b",
name: "Item B Name",
...
},
{
id: "item_a.item_c",
name: "Item C Name",
...
},
{
id: "item_d",
name: "Item D Name",
...
},
{
id: "item_d.item_e",
name: "Item E Name",
...
},
{
id: "item_d.item_e.item_f",
name: "Item F Name",
...
}];
上面是一个非常基本的示例,但这就是输出的样子。
理想情况下我会得到以下结果:
attributes: [
{
id: "item_a",
name: "Item A Name",
nestedAttributes: [{
id: "item_a.item_b"
name: "Item B Name"
...
},
{
id: "item_a.item_c"
name: "Item C Name"
...
}],
...
},
{
id: "item_d",
name: "Item D Name",
nestedAttributes: [{
id: "item_d.item_e"
name: "Item E Name"
nestedAttributes: [{
id: "item_d.item_e.item_f",
name: "Item F Name",
...
}],
...
}],
...
}];
最佳答案
嗯,除了整个结构需要重新思考并且近乎精神 split 这一显而易见的事实之外,答案非常简单。
Here's a jsfiddle that works 。本质上,您只想积累对象,在每个级别检查关键元素。
function build(attr) {
var target, key, out = {},
i = -1,
len = attr.length;
while (++i < len) {
key = attr[i].id.split('.');
target = makeOrFind(out, key);
extend(target, attr[i]);
}
return out;
}
function makeOrFind(target, keyParts) {
var key, i = -1, len = keyParts.length;
while(++i < len) {
key = keyParts[i];
if( i > 0 ) {
if( !target.nestedItems ) { target.nestedItems = {}; }
target = target.nestedItems;
}
if( !target[key] ) { target[key] = {}; }
target = target[key];
}
return target;
}
function extend(target, vals) {
// this is an overly simple implementation of extend
// it only works if your objects are exactly one level deep
// but extend is a solved problem and not really in the scope of the question
for( var key in vals ) {
if( vals.hasOwnProperty(key) ) {
target[key] = vals[key];
}
}
}
var out = build(attr);
console.log(out);
关于javascript - 使用 JavaScript 对 JSON 对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13586682/