Rajesh Ramachandran
Rajesh Ramachandran

Reputation: 71

How to pattern match in javascript object

Is there any lodash method I can used for pattern matching in javascript for the following problem?

I have keys = [x, y, z] and object = { x: 'a', x0: 'a0', y: 'b', y0: 'b1', y1: 'c', k: 'k', k1: 'k1'..}

I need to get the result as { x: 'a', x0: 'a0', y: 'b' , y0: 'b1', y1: 'c'}.

Basically, I need to give an array of keys and an object, and it should return an object with all the keys which have one of the chosen keys as a substring.

Upvotes: 1

Views: 669

Answers (4)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196142

You could use the pickBy but with a custom predicate

const keys = [ 'x', 'y', 'z'];
const object = { x: 'a', x0: 'a0', y: 'b' ,y0:'b1', y1:'c', k:'k' ,k1:'k1'};

const filtered = _.pickBy(object, (value,key)=>keys.some(k=>key.includes(k)));

console.log(filtered);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>


And if you want to reuse this for different keys you can create a "predicate" function to reuse

const keyIncludes = (partialKeys) => (value, key) => partialKeys.some(partialKey => key.includes(partialKey));

const keys = [ 'x', 'y', 'z'];
const object = { x: 'a', x0: 'a0', y: 'b' ,y0:'b1', y1:'c', k:'k' ,k1:'k1'};

const filtered = _.pickBy(object, keyIncludes(keys));

console.log(filtered);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Upvotes: 0

elvira.genkel
elvira.genkel

Reputation: 1333

You can iterate through keys of object and check for keys array

const keys = ['x', 'y', 'z'] 
const object = { x: 'a', x0: 'a0', y: 'b' ,y0:'b1', y1:'c', k:'k' ,k1:'k1'}

// result as = { x: 'a', x0: 'a0', y: 'b' ,y0:'b1', y1:'c'}

const result = Object.keys(object).reduce((acc, rec) => {
  // if current key has sub-string for any value in keys array
  if(keys.filter(it => rec.indexOf(it) > -1).length > 0) {
    return {...acc, [rec]: object[rec]}
  }
  return acc
}, {})

console.log(result)

Upvotes: 0

awarrier99
awarrier99

Reputation: 3855

Not sure about lodash, but you can do this using native JavaScript fairly simply:

const keys = [ 'x', 'y', 'z'];
const object = { x: 'a', x0: 'a0', y: 'b', y0:'b1', y1:'c', k:'k', k1:'k1'};

const validEntries = Object.entries(object)
  .filter(([key, val]) => keys.some(k => key.includes(k)));
const result = Object.fromEntries(validEntries);
console.log(result);

Upvotes: 1

Jared Smith
Jared Smith

Reputation: 21965

Not aware of any lodash method that does this, but it's not that complicated:

const keys = ['x', 'y', 'z'];
const obj = { x: 'a', x0: 'a0', y: 'b' ,y0:'b1', y1:'c' };
const matched = keys.reduce((acc, key) => {
  Object.entries(obj)
    .filter(([k]) => k.includes(key))
    .forEach(([k, v]) => (acc[k] = v));
  return acc;
}, {});

Upvotes: 0

Related Questions