2017-02-03 5 views
2

어쩌면 간단한 작업에 막혔지만 해결책을 찾지 못했습니다.JSON 데이터 매핑이 반대입니까?

[{ 
    "_id": 1, 
    "type": "person", 
    "Name": "Hans", 
    "WorksFor": ["3", "4"] 
}, { 
    "_id": 2, 
    "type": "person", 
    "Name": "Michael", 
    "WorksFor": ["3"] 
}, { 
    "_id": 3, 
    "type": "department", 
    "Name": "Marketing" 
}, { 
    "_id": 4, 
    "type": "department", 
    "Name": "Sales" 
}] 

나는 모든 사람과 그들이 함께 부서의지도 배열을 사용하여 일하는 부서를 얻을 매우 간단 here을 배운 것처럼 - 좀 JSON 데이터가 있다고 가정 할 수 있습니다. 는 다음 나는 사람에게 해당 부서를지도와 같은 것을받을 수 있습니다 :

[{ 
    "_id": 1, 
    "type": "person", 
    "Name": "Hans", 
    "WorksFor": ["3", "4"], 
    "Readable": ["Marketing", "Sales"] 
}, { 
    "_id": 2, 
    "type": "person", 
    "Name": "Michael", 
    "WorksFor": ["3"], 
    "Readable": ["Sales"] 
}] 

을하지만 다른 인터페이스 나 데이터 예를 들어, "둥근 다른 방법"이 필요합니다

[{ 
    "_id": 3, 
    "type": "department", 
    "Name": "Marketing", 
    "employees": [ 
     "Hans", "Michael" 
    ] 
}, { 
    "_id": 4, 
    "type": "department", 
    "Name": "Sales", 
    "employees": [ 
     "Hans" 
    ] 
    }] 

이 구조를 이루기위한 적절한 방법이 있습니까? 노력 2 일간 아무데도 못 찾았 어 ...

+0

코드를 작성 했습니까? –

답변

1

var data = [{ "_id": 1, "type": "person", "Name": "Hans", "WorksFor": ["3", "4"] }, { "_id": 2, "type": "person", "Name": "Michael", "WorksFor": ["3"] }, { "_id": 3, "type": "department", "Name": "Marketing" }, { "_id": 4, "type": "department", "Name": "Sales" }]; 
 

 
var departments = [], 
 
    persons = []; 
 

 
data.forEach(e => { 
 
    if (e.type === "person") { 
 
    persons.push(e); 
 
    } else if (e.type === "department") { 
 
    departments.push(e); 
 
    e.employees = []; 
 
    } 
 
}); 
 

 
departments.forEach(d => { 
 
    var workers = persons.filter(p => p.WorksFor.indexOf(d._id.toString()) > -1) 
 
        /*.map(p => p.Name)*/ // add this if you only need the name instead of the complete "person" 
 

 
    d.employees = d.employees.concat(workers); 
 
}); 
 

 
console.log(JSON.stringify(departments, null, 4));

0

첫 번째 매핑을 얻을 수있는 방법이 있습니다. 나는 여러분이 따라 할 수있는 몇 가지 코멘트를 추가했으며, 두 번째 문제에 대한 답을 찾을 수 있기를 바랍니다.

// First, let's get just the items in this array that identify persons 
// I've called this array "data" 
data.filter(x => x.type === 'person') 
    // Now let's map over them 
    .map(person => 
     // We want all of the data associated with this person, so let's 
     // use Object.assign to duplicate that data for us 
     Object.assign({}, person, { 
      // In addition, we want to map the ID of the WorksFor array to the Name 
      // of the corresponding department. Assuming that the _id key is unique, 
      // we can due this simply by mapping over the WorksFor array and finding 
      // those values within the original array. 
      Readable: person.WorksFor.map(wfId => 
      // Notice here the parseInt. This will not work without it due to 
      // the type difference between WorksFor (string) and _id (integer) 
      data.find(d => d._id === parseInt(wfId)).Name 
     ) 
     }) 
); 
1

이 같은 뭔가를 시도 할 수 있습니다 :

var data = [{ "_id": 1, "type": "person", "Name": "Hans", "WorksFor": ["3", "4"]}, { "_id": 2, "type": "person", "Name": "Michael", "WorksFor": ["3"]}, { "_id": 3, "type": "department", "Name": "Marketing"}, { "_id": 4, "type": "department", "Name": "Sales"}] 
 
var ignoreDept = ['person']; 
 

 
var result = data.reduce(function(p,c,i,a){ 
 
    if(ignoreDept.indexOf(c.type) < 0){ 
 
    c.employees = a.reduce(function(arr,emp){ 
 
     if(emp.WorksFor && emp.WorksFor.indexOf(c._id.toString()) > -1){ 
 
     arr.push(emp.Name) 
 
     } 
 
     return arr; 
 
    },[]); 
 
    p.push(c); 
 
    } 
 
    return p; 
 
}, []); 
 

 
console.log(result)

1

솔루션을 Array.prototype.filter()Array.prototype.forEach() 기능을 사용하여 :

var data = [{ "_id": 1, "type": "person", "Name": "Hans", "WorksFor": ["3", "4"]}, { "_id": 2, "type": "person", "Name": "Michael", "WorksFor": ["3"]}, { "_id": 3, "type": "department", "Name": "Marketing"}, { "_id": 4, "type": "department", "Name": "Sales"}], 
 
    // getting separated "lists" of departments and employees(persons) 
 
    deps = data.filter(function(o){ return o.type === "department"; }), 
 
    persons = data.filter(function(o){ return o.type === "person"; }); 
 
    
 
deps.forEach(function (d) { 
 
    d['employees'] = d['employees'] || []; 
 
    persons.forEach(function (p) { 
 
     if (p.WorksFor.indexOf(String(d._id)) !== -1) { // check the `id` coincidence between the employee and the department 
 
     d['employees'].push(p.Name); 
 
     } 
 
    }); 
 
}); 
 
    
 
console.log(deps);

1

해시 테이블과 각 루프에 대해 단일 루프를 사용할 수 있습니다.

방법 :

  • Array#reduce 결과 배열을 반복 및 반환 내부 배열 WorksFor를 루핑
  • Array#forEach,
  • Object.create(null)
  • 모든 시제품없이 객체를 생성하는
  • 일부 다른 패턴, 마감과 같은 hash
  • 우리 e를 logical OR ||으로 설정하여 위조 값을 확인하고 기본값으로 개체를 가져옵니다.

    hash[b] = hash[b] || { _id: b, employees: [] }; 
    

var data = [{ _id: 1, type: "person", Name: "Hans", WorksFor: [3, 4] }, { _id: 2, type: "person", Name: "Michael", WorksFor: [3] }, { _id: 3, type: "department", Name: "Marketing" }, { _id: 4, type: "department", Name: "Sales" }], 
 
    result = data.reduce(function (hash) { 
 
     return function (r, a) { 
 
      if (a.type === 'person') { 
 
       a.WorksFor.forEach(function (b) { 
 
        hash[b] = hash[b] || { _id: b, employees: [] }; 
 
        hash[b].employees.push(a.Name); 
 
       }); 
 
      } 
 
      if (a.type === 'department') { 
 
       hash[a._id] = hash[a._id] || { _id: b, employees: [] }; 
 
       hash[a._id].type = a.type; 
 
       hash[a._id].Name = a.Name; 
 
       r.push(hash[a._id]); 
 
      } 
 
      return r; 
 
     }; 
 
    }(Object.create(null)), []); 
 

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

0

var data = [{ "_id": 1, "type": "person", "Name": "Hans", "WorksFor": ["3", "4"]}, { "_id": 2, "type": "person", "Name": "Michael", "WorksFor": ["3"]}, { "_id": 3, "type": "department", "Name": "Marketing"}, { "_id": 4, "type": "department", "Name": "Sales"}]; 
 

 
var dep = {}; 
 

 
data.forEach(e => (e.type === 'person' && e.WorksFor.forEach(d => dep[d]? dep[d].push(e.Name): dep[d] = [e.Name]))); 
 

 
data.forEach(e => (e.type == 'department' && (e.employees = dep[e._id] || []))); 
 

 
data = data.filter(e => e.type == 'department'); 
 

 
console.log(data);
,536,

관련 문제