Does js have a way to delete an attribute in an object without changing the original object?
problem description
case: there is a Form form in which the data is an obj object. When the attribute a
satisfies the condition 1, it needs to be deleted. Is there any way not to affect whether the obj
object still contains a
attributes.
let obj = {
a: 1,
b: 2,
c: 3
}
obj.a == 1 && delete obj.a;
console.log(obj);
Can
be solved by deconstruction and other methods?
< hr >
-first update-
Let me explain why I did this.
because I need to ensure the integrity of this field in state
(react). Because page components need to render their values. The value of axi1
does not need to be removed when I pass it, but the original object cannot be directly removed. There are too many attributes to deconstruct directly ~
< hr >
-second update-
is there a way to deconstruct? Before, I wanted to change the value by changing the practice of the object, the risk is too great. Now I want to deal with it directly in the place where the parameters are passed. Because the parameters are not fixed, it is not possible to directly deconstruct
submit: submit (Object.assign ({}, bjournal c);)
let {a,...obj} = {a:1,b:2,c:3};
obj//{b: 2, c: 3}
let {aMagne.obj} = {aVera 1answer 2 < hr class=
let {aqin .b} = obj;
if (astat1) {
obj = b
}
obj.a = = 1 & & obj.a = undefined;
what does it mean to delete an attribute and include an attribute?
deeply copy a new object and do processing on the new object, so that the original object is not affected, and the data passed to the background is guaranteed to be OK
.
this question is a little unclear, what is both deleted and unchanged.
asks whether deep clone , obj0 clone obj1,obj0 removes the attribute, obj1 remains the same.
or sets a property of the object to non-enumerable . The data exists and can be manipulated, but will not be traversed.
Deep cloning
//
// var obj0 = { a:1, b:'2', c:[true,null,{cc:'cc'}], d:function(){ console.log("run") } }
// var newObj = objClone(obj0);
// console.log(newObj);
// initalObj,
// finalObj,
// attrsobj,
// filterFlagtrueattrs,falseattrs
function objClone(initalObj, finalObj, attrs, filterFlag){
var o = finalObj ? objClone(finalObj) : initalObj instanceof Array ? [] : {};
if(initalObj && typeof initalObj == 'object' && initalObj.constructor !== Object) {
o.__proto__ = initalObj.__proto__
}
for(var k in initalObj) {
if(attrs && !!filterFlag == (attrs.indexOf(k) == -1)){
continue;
}
o[k] = (initalObj[k] && typeof(initalObj[k]) === 'object') ? objClone(initalObj[k]) : initalObj[k];
}
return o;
}
1. Maintain an array or object to store what needs to be displayed
let obj = {
a: 1,
b: 2,
c: 3
}
let arr = ['b','c']
2. Give it directly to the object
let obj = {
a: {value: 1,show:false},
b: {value: 2,show:true},
c: {value: 3,show:true}
}
lazy method JSON.stringify then JSON.parse and then delete the attribute.
JSON.parse(JSON.stringify({a:1,b:2,c:3}, ['a', 'b'])) // {a: 1, b: 2}