5

Bu benim yapıyorum nasıl: Bir temizleyici, daha basit bir yoluSığ nesne nesnesini ES6/ES7 içinde bir veya daha fazla özelliği mi bırakıyorsunuz?

var props = { id: 1, name: 'test', children: [] } 
 

 
//copy props but leave children out 
 
var newProps = { ...props } 
 
delete newProps.children 
 

 
console.log(newProps) // { id: 1, name: 'test' }

var mı?

+0

(zaten kullandığınız aynı rest/spread properties proposal for ES7 ile)

var props = { id: 1, name: 'test', children: [] } var {children:_, ...newProps} = props; console.log(newProps) // { id: 1, name: 'test' } console.log(_) // [] - as an "empty" placeholder 

. En önemli satırı yazmadınız, yeni provalara sahne kopyaladığınız yer. "..." nedir? – Gavriel

+0

@ william.taylor.09, çoğaltılmamış. Nasıl kopyalanacağını bilir (sadece bu satırı göstermez) ama bir kara listeye dahil olmak üzere tüm özellikleri kopyalamak istiyor. – Gavriel

+0

@Gavriel bu satırın temel özelliklerini sığdırmayacak şekilde yeni nesneyi 'var newProps = {.. .props} '? Yapmak gibi çeşit var newProps = Object.assign ({}, sahne) ' –

cevap

8

Sen kullanabileceği bir destructuring assignment: Anlamıyorum

+0

Evet, bence bu en iyi seçenek - Daha önce benzer bir şey yapıyordum. Ben sadece daha açık bir şey olsaydı keşke ... –

+0

Ben zaten oldukça açık bence… İsterseniz, uygun adlandırılmış bir işlev yazabilirsiniz '(tuş, {[anahtar]: _, ... dinlenme}) => dinlenme ve bunu çağır. – Bergi

+1

'/ * eslint no-unused-vars: [" error ", {" varsIgnorePattern ":" _ "] * /' Bu tekniği kullanırken eslint hatalarından kurtulmak yararlıdır. – icc97

1

var props = { id: 1, name: 'test', children: [] } 
 

 
function clone(orig, blacklistedProps) { 
 
    var newProps = {}; 
 
    Object.keys(props).forEach(function(key) { 
 
     if (!blacklistedProps || blacklistedProps.indexOf(key) == -1) { 
 
      newProps[key] = props[key]; 
 
     } 
 
    }); 
 
    return newProps; 
 
} 
 
var newProps = clone(props, ['children']); 
 
console.log(newProps) // { id: 1, name: 'test' } 
 
var newProps1 = clone(props); 
 
console.log(newProps1) // { id: 1, name: 'test', children:[] }

+0

Teşekkürler @gavriel. Evet, sanırım mantığımı bir klonlama fonksiyonuna sokabilirim. Sadece daha özlü bir yol olduğunu umuyordum. –