다음을 포함하는 지역이라는 배열이 있습니다.
나는 해시 맵을 만들고 싶습니다.
key는 id [지역에있는 각 개체의 id 속성]입니다.
그리고
값은 전체 개체입니다.
같은 도움말 / 포인터가 있습니까?
감사합니다
안녕하세요 당신은 그렇게 할 수 있으며 작동합니다.
var hashmap = {};
territory.forEach(function(element) {
if(hashmap[element.id]!==null && hashmap[element.id]!=undefined){
if(!Array.isArray(hashmap[element.id])){
var tempObj = hashmap[element.id];
// don't forget to json.stringify your object if you
// want to serialise your hashmap for external use
hashmap[element.id] = [tempObj];
}
hashmap[element.id].push(element);
}
else{
// if you want to serialise your hashmap for external use
hashmap[element.id] = JSON.stringify(element);
// if not, you could just do without JSON.stringify
hashmap[element.id] = element;
}
});
console.log(hashmap);
foreach에 대한 자세한 정보는 mozilla 문서를 참조하십시오.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
편집 : (더러운) ID 중복을 방지하고 동일한 ID를 공유하는 객체를 저장하기 위해 코드를 업데이트했습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다