programing

개체에서 속성을 불변으로 제거

telebox 2023. 10. 14. 10:03
반응형

개체에서 속성을 불변으로 제거

저는 Redux를 사용하고 있습니다.축소기에서 다음과 같은 객체에서 속성을 제거하려고 합니다.

const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}

원래 상태를 변형시키지 않고 이런 것을 먹고 싶습니다.

const newState = {
    a: '1',
    b: '2',
    c: {
       x: '42',
    },
}

노력했습니다.

let newState = Object.assign({}, state);
delete newState.c.y

그러나 어떤 이유로 두 주에서 모두 삭제됩니다.

제가 그것을 하는데 도움이 될까요?

파괴 과제 구문을 사용하는 것은 어떻습니까?

const original = {
  foo: 'bar',
  stack: 'overflow',
};

// If the name of the property to remove is constant
const { stack, ...withoutFirst } = original;
console.log(withoutFirst); // Will be { "foo": "bar" }

// If the name of the property to remove is from a variable
const key = 'stack'
const { [key]: value, ...withoutSecond } = original;
console.log(withoutSecond); // Will be { "foo": "bar" }

// To do a deep removal with property names from variables
const deep = {
  foo: 'bar',
  c: {
   x: 1,
   y: 2
  }
};

const parentKey = 'c';
const childKey = 'y';
// Remove the 'c' element from original
const { [parentKey]: parentValue, ...noChild } = deep;
// Remove the 'y' from the 'c' element
const { [childKey]: removedValue, ...childWithout } = parentValue;
// Merge back together
const withoutThird = { ...noChild, [parentKey]: childWithout };
console.log(withoutThird); // Will be { "foo": "bar", "c": { "x": 1 } }

다음과 같은 ES5 어레이 방법을 찾습니다.filter,map그리고.reduce항상 새로운 배열이나 객체를 반환하기 때문에 유용합니다.이 경우엔 제가 사용할 겁니다.Object.keys그 물체 위를 반복하는 것, 그리고Array#reduce다시 물체로 바꾸는 것.

return Object.assign({}, state, {
    c: Object.keys(state.c).reduce((result, key) => {
        if (key !== 'y') {
            result[key] = state.c[key];
        }
        return result;
    }, {})
});

사용가능_.omit(object, [paths])로다시 도서관에서

경로는 다음과 같이 중첩될 수 있습니다._.omit(object, ['key1.key2.key3'])

ES6 객체 파괴 기능만 사용

const state = {
    c: {
       x: '42',
       y: '43'
    },
}

const { c: { y, ...c } } = state // generates a new 'c' without 'y'

console.log({...state, c }) // put the new c on a new state

그것은 당신이 다음의 값을 복사하고 있기 때문입니다.state.c다른 목적으로.그리고 그 값은 다른 자바스크립트 객체를 가리키는 포인터입니다.따라서 이 두 포인터 모두 동일한 개체를 가리킵니다.

시도해 보기:

let newState = Object.assign({}, state);
console.log(newState == state); // false
console.log(newState.c == state.c); // true
newState.c = Object.assign({}, state.c);
console.log(newState.c == state.c); // now it is false
delete newState.c.y;

개체를 심층 복사할 수도 있습니다.이 질문을 보시면 자신에게 가장 적합한 것을 찾을 수 있을 것입니다.

이거 어때:

function removeByKey (myObj, deleteKey) {
  return Object.keys(myObj)
    .filter(key => key !== deleteKey)
    .reduce((result, current) => {
      result[current] = myObj[current];
      return result;
  }, {});
}

삭제해야 할 키를 필터링한 다음 나머지 키와 초기 개체에서 새 개체를 생성합니다.타일러 맥기네스의 놀라운 반응 프로그램에서 아이디어를 도둑맞았습니다.

제이에스빈

2019년 현재, 또 다른 옵션은 다음을 사용하는 것입니다.Object.fromEntries방법.4단계에 이르렀습니다.

const newC = Object.fromEntries(
    Object.entries(state.c).filter(([key]) => key != 'y')
)
const newState = {...state, c: newC}

이것의 좋은 점은 정수 키를 잘 다룬다는 것입니다.

function dissoc(key, obj) {
  let copy = Object.assign({}, obj)
  delete copy[key]
  return copy
}

또한, 기능적인 프로그래밍 툴킷을 찾고 있다면, Ramda를 보세요.

다음과 같은 경우에는 불변성 도우미를 사용하여 속성을 설정 해제할 수 있습니다.

import update from 'immutability-helper';

const updatedState = update(state, {
  c: {
    $unset: ['y']
  }
});    

Immutible.js를 사용하면 간단합니다.

const newState = state.deleteIn(['c', 'y']);

deleteIn() 설명

제거하고 싶은 소품을 부분적으로 적용할 수 있는 간편한 1라이너가 있습니다.이를 통해 에 쉽게 전달할 수 있습니다.Array.map.

const removeProp = prop => ({ [prop]: _, ...rest }) => ({ ...rest })

이제 다음과 같이 사용할 수 있습니다.

const newArr = oldArr.map(removeProp('deleteMe'))

문제는 초기 상태를 심층적으로 복제하지 않는다는 것입니다.당신은 복사본이 얕군요.

스프레드 연산자를 사용할 수 있습니다.

  const newState = { ...state, c: { ...state.c } };
  delete newState.c.y

아니면 당신과 같은 코드를 따르거나.

let newState = Object.assign({}, state, { c: Object.assign({}, state.c) });
delete newState.c.y

제가 평소에.

Object.assign({}, existingState, {propToRemove: undefined})

나는 이것이 실제로 부동산을 제거하는 것이 아니라 거의 모든 목적에서 그것이 기능적으로 동등하다는 것을 알고 있습니다.이것에 대한 구문은 제가 생각하기에 꽤 좋은 절충안보다 훨씬 간단합니다.

1 사용하시는 경우hasOwnProperty()은 더 가 있을 입니다.

이 무늬를 사용합니다.

const newState = Object.assign({}, state);
      delete newState.show;
      return newState;

그러나 책에서 나는 또다른 패턴을 보았습니다.

return Object.assign({}, state, { name: undefined } )

효용 ;)

const removeObjectField = (obj, field) => {

    // delete filter[selectName]; -> this mutates.
    const { [field]: remove, ...rest } = obj;

    return rest;
}

액션타입

const MY_Y_REMOVE = 'MY_Y_REMOVE';

액션 크리에이터

const myYRemoveAction = (c, y) => {

    const result = removeObjectField(c, y);

        return dispatch =>
            dispatch({
                type: MY_Y_REMOVE,
                payload: result
            })
    }

감속기

export default (state ={}, action) => {
  switch (action.type) {
    case myActions.MY_Y_REMOVE || :
      return { ...state, c: action.payload };
    default:
      return state;
  }
};

이미 일부 답변에서 암시된 바와 같이, 중첩 상태를 수정하려고 하기 때문입니다.한 단계 더 깊이 표준적인 해결책은 위에 감속기를 추가하는 것입니다에 입니다.x상태 수준:

const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}

더 깊은 레벨 감소기

let newDeepState = Object.assign({}, state.c);
delete newDeepState.y;

원레벨감속기

let newState = Object.assign({}, state, {c: newDeepState});

Object.assign, JSON.parse 및 JSON.stringify를 조합하여 사용합니다.

const obj1 = { a: "a", b: "b" };
const obj2 = { c: "c", a: undefined };

const merged = Object.assign({}, obj1, obj2);

const sanitized = JSON.parse(JSON.stringify(merged));

console.log(sanitized); // -> { b: "b", c: "c" }

언급URL : https://stackoverflow.com/questions/34401098/remove-a-property-in-an-object-immutably

반응형