2017-06-29 45 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