5

If I have an object, such as,

const obj = {
  a: 1,
  b: 2,
  c: 3,
}

I can map the keys and values as,

Object.entries(obj).map(([key, value]) => console.log(`${key}: ${value}`))

Is it possible in Javascript to omit a property, when mapping it?

Something like,

Object.entries({a: obj.a, ...obj}).map(([key, value]) => console.log(`${key}: ${value}`))

I can do the following:

Object.entries(obj).map(([key, value]) => key !== 'a' && console.log(`${key}: ${value}`))

But I feel like there can be a cleaner way to do this, and also this wouldn't work, because that mapped index will contain undefined. Just looking to clarify this.

7
  • 3
    Why are you using .map() here in the first place? You're not returning anything. Seems like you are using it as a .forEach(). Commented Jul 22, 2020 at 14:15
  • 3
    If you want to skip properties I'd just chain a .filter() and then a .map() Commented Jul 22, 2020 at 14:16
  • I'm mapping an object to JSX elements, and I need to exclude a specific key from a form data object. Commented Jul 22, 2020 at 14:16
  • 1
    @MikeK If you're mapping to jsx elements, then please show us the actual code that does that. Commented Jul 22, 2020 at 14:22
  • 1
    Perhaps useful is const filterMap = (f, m) => (xs) => xs .flatMap ((x) => f (x) ? [m (x)] : []) Commented Jul 22, 2020 at 14:40

3 Answers 3

3

you can use filter

Object.entries(obj).filter(([key, _]) => key !== "a").map();
Sign up to request clarification or add additional context in comments.

2 Comments

You can use reduce after the filter to get an object back from the entries array. Object.entries(obj).filter(([key, _]) => key !== "a").reduce((res, [key, value]) => ({ ...res, [key]: value}), {});
@FilipePinheiro OP doesn't want that? And no, you shouldn't use reduce for that, just call Object.fromEntries :-)
3

If you want to hide/exclude a key when using a map you can set its enumerable property to false, using Object.defineProperty:

const obj = {
  a: 1,
  b: 2,
  c: 3,
}

// this will hide key 'b' from obj
Object.defineProperty(obj, 'b', {
  enumerable: false,  
});

Object.entries(obj).map(([key, value]) => console.log(`${key}: ${value}`))

Comments

2

Here is what you want:

const obj = {
    a: 1,
    b: 2,
    c: 3,
}


const res = Object.entries(obj).filter(([key, value]) => key !== 'a');

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.