Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an object by partial paths

Tags:

javascript

How to filter an object given its partial path?

As an example.

let address  = {
  country :{
    name:'Japan',
    city:{
      name:'Tokyo',
      town: {
        name:'korushawa'
      }
    },
    code:'JP'
  },
  nearbyCountry:'Korea'
}

path1: countr.cit

For address, path1 will result in

{
  country :{
    city:{
      name:'Tokyo',
      town: {
        name:'korushawa'
      }
    }
  }
}


path2: countr

For path2, I should get entire address object because countr is present in country and nearbyCountry

{
  country :{
    name:'Japan',
    city:{
      name:'Tokyo',
      town: {
        name:'korushawa'
      }
    }
  },
  nearbyCountry:'Korea'
}

Edit: I have been able to solve this when given an exact path (ex: country.city). But having difficulty with partial paths.

like image 591
asdasd Avatar asked Dec 14 '22 12:12

asdasd


1 Answers

This approach rely on filtering the entries and rebuilding a new object by mapping objects with a single property.

function getParts(object, fragments) {
    var [part, ...rest] = fragments.split('.');

    return Object.assign({}, ...Object
        .entries(object)
        .filter(([key]) => key.toLowerCase().includes(part))
        .map(([k, v]) => {
            if (!rest.length) return { [k]: v };
            var parts = v && typeof v === 'object' && getParts(v, rest.join('.'));
            if (parts) return { [k]: parts };
        })
    );
}

let address = { country: { name: 'Japan', city: { name: 'Tokyo', town: { name: 'korushawa' } }, code: 'JP' }, nearbyCountry: 'Korea' };

console.log(getParts(address, 'countr.cit'));
console.log(getParts(address, 'countr'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 66
Nina Scholz Avatar answered Dec 21 '22 10:12

Nina Scholz