如何在React中创建状态数据减去某些属性的副本



我有要转换为JSON(如(的状态数据

state = {
name: “John”
age: 24
height: “180cm”
id: 2
}

如何创建此状态减去id属性的副本?

所以

copy = {
name: “John”
age: 24
height: “180cm”
}

我试过使用filter函数,但它似乎对此不起作用。状态?

任何帮助都会很棒。

const { id, ...copy } = state;

这种析构函数赋值导致id和一个名为copy的对象的本地声明,该对象包含state的所有剩余键(和值(,这些键是而不是id

有关上下文,请参见以下代码段。

const state = {
name: 'John',
age: 24,
height: '180 cm',
id: 2
};
const { id, ...copy } = state;
console.log(copy);

var state = {
name: 'John',
age: 24,
height: '180 cm',
id: 2
};
// you need to filter the keys of the object
var keysToKeep = Object.keys(state).filter(key => key != 'id');
var copy = keysToKeep.reduce((acc, key) => {
acc[key] = state[key];
return acc;
}, {});
console.log(copy);

你可以简单地做到这一点,

let state = {
name: "John",
age: 24,
height: "180cm",
id: 2
}
let copy = {}
Object.keys(state).forEach(k => {
if(k !== 'id') {
copy[k] = state[k]
}
})
console.log(copy)

我将采用的方法称为析构函数,它看起来像这样:

{name,age,height}= this.state;

然后将所有元素复制到一个新的变量

const copystate= {name,age,height}
const obj = {
name: "John",
age: 24,
height: "180cm",
id: 2
}
const { id, ...rest} = obj;

rest现在是除id之外的所有属性

如果您在项目中有lodash

import omit from 'lodash/omit';
const newState = omit(oldState, ['id']);

如果你还没有在项目

const { id, ...newState } = oldState;

这样做:

const state = {
name: "John",
age: 24,
height: "180cm",
id: 2
}
const newState = {...state}
delete newState.id

这将创建一个newState对象,而不是操作原始的state对象(这会导致问题(。然后它将更新newState对象以移除id

然后可以继续使用newState对象。

最新更新