Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript에서 대괄호 개체 키를 중첩 개체로 변환하는 방법은 무엇입니까?

<시간/>

JavaScript에서 Object 내의 중첩 키에 액세스할 수 있는 두 가지 방법이 있다는 것을 알고 있습니다.

예를 들어 이 개체를 가져오십시오 -

const obj = {
   object: {
      foo: {
         bar: {
            ya: 100
         }
      }
   }
};

중첩 속성 'ya'에 액세스하거나 업데이트해야 하는 경우 다음과 같이 액세스할 수 있습니다. -

방법 1 -

obj['object']['foo']['bar']['ya']

또는 방법 2 -

obj.object.foo.bar.ya

이 두 가지 방법 모두 우리를 같은 목적지로 이끕니다.

Way 1에서 설명한 것처럼 중첩 키의 경로를 문자열로 받아 Way 2에서 설명한 표기법으로 변환하는 JavaScript 함수를 작성해야 합니다.

예시

이에 대한 코드는 -

const obj = { "object[foo][bar][ya]": 100 };
const constructDotNotation = obj => {
   const keys = Object.keys(obj)[0].split('[').map(el => {
      return el.replace(']', '');
   });
   let res = {};
   keys.reverse().forEach(key => {
      if (Object.keys(res).length === 0){
         res[key] = obj[Object.keys(obj)[0]];
      }else{
         const temp = {};
         temp[key] = res;
         res = temp;
      };
   });
   return res;
};
console.log(JSON.stringify(constructDotNotation(obj), undefined, 4));

출력

콘솔의 출력은 -

{
   "object": {
      "foo": {
         "bar": {
            "ya": 100
         }
      }
   }
}