3

So i want to filter object of objects, and print all of them except one, which i specify by key.

const obj = {1: {age: 10}, 2: {age: 20}};

console.log(obj);

So i must have option to somehow specify that i don't want the obj[1] to be printed. How do i do that? : |

  • I don't want to delete anything from it.
Mike
  • 49
  • 5

2 Answers2

5

You could destructure the object:

const obj = {1: {age: 10}, 2: {age: 20}, 3: {age: 30}},
      key = 1;
      
const { [key]:_, ...rest } = obj
console.log(rest);
adiga
  • 34,372
  • 9
  • 61
  • 83
4

You can filter() the keys and then convert it back to object using reduce()

const obj = {1: {age: 10}, 2: {age: 20}};

let key = 1
console.log(Object.keys(obj).filter(x => x != key).reduce((ac,a) => ({...ac,[a]:obj[a]}),{}));

Using the new feature Object.fromEntries

const obj = {1: {age: 10}, 2: {age: 20}};

let key = 1
let res = Object.fromEntries(Object.entries(obj).filter(x => x[0] != key));
console.log(res);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73