javascriptobjectfilter

Filter nested object


I receive an object that looks like this:

 this.tokensData = {
    O: {
        id: 0,
        name: value1,
        organization: organization1,
        ...,
       },
    1: {
        id: 1,
        name: value1,
        organization: organization1,
        ...,
        },
    2: {
        id: 2,
        name: value2,
        organization: organization2,
        ...,
        },
    ...
   }

I want to filter by id and remove the Object which id matches the id I receive from the store. What I tried so far:

const filteredObject = Object.keys(this.tokensData).map((token) => {
  if (this.$store.state.id !== this.tokensData[token].id) {
    return this.tokensData[token];
  }
});

This replaces the Object with undefined - which would work for my purposes but is obviously not ideal. Any help is much appreciated!


Solution

  • Try to use Object.entries and then Object.fromEntries() to create an object from a list of key-value pairs:

    const store = [0 , 1];
    
    const result = Object
       .entries(tokensData)
       .filter(([k, v]) => !store.some(s => s == v.id));
    
    console.log(Object.fromEntries(result));
    

    An example:

    const tokensData = {
       O: {
           id: 0,
           name: '',
           organization: '',
          },
       1: {
           id: 1,
           name: '',
           organization: '',
           },
       2: {
           id: 2,
           name: '',
           organization: '',
           }
      }
    
    const store = [0 , 1];
    
    const result = Object
        .entries(tokensData)
        .filter(([k, v]) => !store.some(s => s == v.id));
    
    console.log(Object.fromEntries(result));