1

I have an object and I want to remove all values except the one that matches a particular key. For example, I could do this:

function remove(obj, key) {
  var value = obj[key]
  var ret = {}
  ret[key] = obj[key]
  obj = ret
}

Or I could iterate:

for (var k in obj) {
  if (k != key) {
    delete obj[k]
  }
}

But I'm wondering if there's a better way. Creating a temporary variable and iterating over the entire object both seem unnecessary. My initial attempt was:

obj = {
  key: obj[key]
}

But that resulted in an object with a key of key.

freginold
  • 3,946
  • 3
  • 13
  • 28
ewok
  • 20,148
  • 51
  • 149
  • 254

2 Answers2

1

You can indeed achieve what you described without using temporary variables.

function remove(obj, key) {
  return Object.assign({}, { [key] : obj[key]});
}
kharhys
  • 257
  • 1
  • 3
0

You can just create a new object with [key]:obj[key].

var obj = {
 "a":1,
 "b":2
};
var key = "a";

function filterByKey(object, key) {
    return Object.create({[key]:obj[key]});
}
function filterByKey2(object, key) {
    return {[key]:obj[key]};
}
console.log(filterByKey(obj, key));
console.log(filterByKey2(obj, key));
Timmetje
  • 7,641
  • 18
  • 36