2016-05-18 5 views
-2

Wie wir nur umwandeln können 'Item' (Objekttyp) Schlüssel zum Array-Typ:separate Array tief Schlüssel zum gewünschten Typ (Array oder Objekt)

var arr = [{ 
    "title": "Custom title", 
    "id": "id1", 
    "icon": "fa fa-reorder", 
    "other": { 
    "3991": { 
     "title": "Some title", 
     "link": "#", 
     "icon": "", 
     "items": { 
     "3992": { 
      "title": "Some title", 
      "link": "#", 
      "icon": "" 
     } 
     } 
    }, 
    "3993": { 
     "title": "Some title", 
     "link": "#", 
     "icon": "" 
    } 
    } 
}]; 

An:

var arr = [{ 
    "title": "Custom title", 
    "id": "id1", 
    "icon": "fa fa-reorder", 
    "other": { 
    "3991": { 
     "title": "Some title", 
     "link": "#", 
     "icon": "", 
     "items": [{ 
      "title": "Some title", 
      "link": "#", 
      "icon": "" 
     }] 
    }, 
    "3993": { 
     "title": "Some title", 
     "link": "#", 
     "icon": "" 
    } 
    } 
}]; 

I muss jedes Mal einzeln auswählen, um welchen Typ der Schlüssel geändert wird. Ich habe nach einigen Array-Walker gesucht, aber ohne Erfolg.

Beispiel:

var newArr = change_key_type({ 
'arr' : arr, 
'key' : 'items', 
'type' : 'array' 
}); 

Antwort

0

könnten Sie durchlaufen und bauen ein neues Array für alle items.

function walk(a) { 
 
    typeof a === 'object' && Object.keys(a).forEach(function (k) { 
 
     if (k === 'items' && typeof a.items === 'object') { 
 
      a.items = Object.keys(a.items).map(function (k) { 
 
       walk(a.items[k]); 
 
       return a.items[k]; 
 
      }); 
 
      return; 
 
     } 
 
     walk(a[k]); 
 
    }); 
 
} 
 

 
var arr = [{ "title": "Custom title", "id": "id1", "icon": "fa fa-reorder", "other": { "3991": { "title": "Some title", "link": "#", "icon": "", "items": { "3992": { "title": "Some title", "link": "#", "icon": "" } } }, "3993": { "title": "Some title", "link": "#", "icon": "" } } }]; 
 

 
arr.forEach(walk); 
 
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');

+0

Dank für neue Ideen. Aber wenn der Schlüssel nicht in der ersten Ebene vorhanden ist, wird der Prozess des Gehens gestoppt ... – Vital

+0

Ja, Ihre Datenstruktur impliziert das. –

+0

Hauptproblem bestehen genau darin. Vielleicht haben Sie einige Ideen, wie Sie es lösen können? – Vital

Verwandte Themen