From an object, extract properties with names matching a test

Viewed 59

I have a props object which will contain an unknown set of properties, some of which I want to extract based on their prefix. I have something that works (great!) but it seems long-winded, and I want to know if there's a more idiomatic way of doing it?

const props = {
  bingo: 1,
  bongo: 2,
  mingo: 3,
  bango: 4
}
const bFields = {}
Object.keys(props).filter(k => (k.startsWith('b'))).forEach(k => (
  bFields[k] = props[k]
))

console.log(props)
console.log(bFields)

4 Answers

How about this one-liner

let props = {bingo:1,bongo:2,mingo:3,bango:4}, filteredProps = {};
Object.keys(props).forEach(x => x.startsWith('b') ? filteredProps[x] = props[x] : '');

console.log(filteredProps);

You can also use reduce:

const props = {
  bingo: 1,
  bongo: 2,
  mingo: 3,
  bango: 4
}
const bFields = Object.keys(props).reduce((acc, prop) => {
  if (prop.startsWith('b')) {
    acc[prop] = props[prop]
  }

  return acc
}, {})

console.log(props);
console.log(bFields);

You can also use Object.fromEntries, Object.entries

const props = {"bingo":1,"bongo":2,"mingo":3,"bango":4}
const bFields = Object.fromEntries(Object.entries(props).filter(([k])=>k.toLowerCase().startsWith('b')))
console.log(bFields)

I did it with the goal "More understandable by someone that doesn't code" I don't know if it was that but here is the code.

const props = {
  bingo: 1,
  bongo: 2,
  mingo: 3,
  bango: 4
}
const bFields = {};
function matchByStart (key, idx, all) {
  if (key.toLowerCase().startsWith("b")) bFields[key] = props[key];
}
Object.keys(props).map(matchByStart);
console.log(bFields);

Hope it helps!

edit: Also I put the method toLowerCase()!

Related