2017-06-29 46 views
0

我有數組對象,我想刪除一些內部對象如果密鑰不匹配。如何篩選對象通過檢查關鍵

輸入:

"configuration" : { 
    "11111-2222-3333-444--5555" : { 
     "home1" : 
      { 
       "tel" : "125", 
       "address" : true, 
      } 
    }, 
    "2222-3333-44444-5555--66666" : { 
     "home2" : 
      { 
       "tel" : "125", 
       "address" : true, 
      } 
    } 
} 

我有一個匹配的字符串11111-2222-3333-444--5555

預期了:

"configuration" : { 
    "11111-2222-3333-444--5555" : { 
     "home1" : 
      { 
       "tel" : "125", 
       "address" : true 
      } 
     } 

    } 
+4

它不是對象的數組。它只是一個有多個鍵的對象。 –

+0

你試過了什麼? –

+0

可能的重複 - https://stackoverflow.com/questions/38750705/using-es6-to-filter-object-properties – Rastalamm

回答

1

使用_.pick()得到你想要的關鍵:

var data = {"configuration":{"11111-2222-3333-444--5555":{"home1":{"tel":"125","address":true}},"2222-3333-44444-5555--66666":{"home2":{"tel":"125","address":true}}}}; 
 

 
var searchKey = '11111-2222-3333-444--5555'; 
 

 
var result = { 
 
    configuration: _.pick(data.configuration, searchKey) 
 
}; 
 

 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

+0

謝謝,解決了我的問題,極大的答案 – thomas

+0

@thomas:如果你發現這個答案是有用的,請點擊灰色接受✓。 –

0

你可以通過鑰匙環和刪除那些你不想要的:

let o = { 
    configuration: { /* etc. */ } 
} 

for(let key in o.configuration) { 
    if(key !== '11111-2222-3333-444--5555') { 
    delete o[key] 
    } 
} 

但是,如果你只是移除一個鍵,那麼這是不必要的。爲了簡化它,你可以這樣做:

let newObject = { 
    configuration: { 
    '11111-2222-3333-444--5555': o.configuration['11111-2222-3333-444--5555'] 
    } 
} 
+0

我使用lodash,選秀是一個很好的功能,還是要謝謝你 – thomas