0

I have array objects, and I want to remove some inner objects if the key is not match.

Input:

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

I have a match string 11111-2222-3333-444--5555

The expected out:

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

   }
ɢʀᴜɴᴛ
  • 32,025
  • 15
  • 116
  • 110
Elizabeth
  • 47
  • 9

2 Answers2

1

Use _.pick() to get the key you want:

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>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

You can loop through the keys and delete the ones you don't want:

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

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

However this is unnecessary if you're removing all but just one key. To simplify it, you could do:

let newObject = {
  configuration: {
    '11111-2222-3333-444--5555': o.configuration['11111-2222-3333-444--5555']
  }
}
Josh Beam
  • 19,292
  • 3
  • 45
  • 68