3

オブジェクトの配列を json オブジェクトに変更するには、JS ループが必要です。オブジェクトのサンプル配列は次のとおりです。

var employees= [
  {name:"Jeff",manager:null,title:"The Pres"},
  {name:"Amy",manager:"Aaron",title:"lll"},
  {name:"Chris",manager:"Aaron",title:"lll"},
  {name:"Dana",manager:"Aaron",title:"lll"},
  {name:"Joe",manager:"Aaron",title:"lll"},
  {name:"Mike",manager:"Aaron",title:"lll"},
  {name:"Aaron",manager:"Jeff",title:"lll"}
];

予想される json オブジェクトは次のとおりです。

var json = {
    name:"Jeff",
    title:"The Pres",
    children:[{
        name:"Aaron",
        title:"some title",
        children[
            {name:"Amy",title:"some title",children[]},
            {name:"Chris",title:"some title",children:[]},
            {name:"Dana",title:"some title",children:[]},
            {name:"Joe",title:"some title",children:[]},
            {name:"Mike",title:"some title",children:[]
        }]
    }]
};

しかし、それは私を超えています。

4

2 に答える 2

5
var employees= [
  {name:"Jeff",manager:null,title:"The Pres"},
  {name:"Amy",manager:"Aaron",title:"lll"},
  {name:"Chris",manager:"Aaron",title:"lll"},
  {name:"Dana",manager:"Aaron",title:"lll"},
  {name:"Joe",manager:"Aaron",title:"lll"},
  {name:"Mike",manager:"Aaron",title:"lll"},
  {name:"Aaron",manager:"Jeff",title:"lll"}
];

​var hash = {};
var root;

for (var i = 0; i < employees.length; i++) {
    var employee = employees[i];
    hash[employee.name] = {
        name:employee.name, manager:employee.manager, title:employee.title, children: []
    };
}
for (var i = 0; i < employees.length; i++) {
    var employee = hash[employees[i].name];
    var manager = hash[employee.manager];
    if (manager) {
        manager.children.push(employee);
    } else {
        root = employee;
    }
}
// root is the employee without a manager

Jsフィドル

于 2012-09-05T17:56:07.667 に答える