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.
0

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.