Rey
Rey

Reputation: 1433

Using `map` to Create New Array of Objects with Fewer Properties

I am wanting to use map to create a new array of of objects that have two properties from the original objects in the originating array, so I am trying this:

const filteredConfigurableModules = configurableModules.map(module =>
  module.name, module.configurables
);

But this isn't working, as only the "name" is saved to the new array. What am I missing here?

I also tried this:

const filteredConfigurableModules = configurableModules.map(module => {
  name: module.name,
  configurables: module.configurables
});

... but end up with a syntax error:

SyntaxError: Unexpected token ':'

Upvotes: 2

Views: 1094

Answers (4)

Ele
Ele

Reputation: 33726

You should wrap it with parentheses as follow:

const filteredConfigurableModules = configurableModules.map(({name, configurables})=> ({
  name,
  configurables
}));

Upvotes: 1

Ekin Alcar
Ekin Alcar

Reputation: 135

Can you try this if i understand your question correctly

const filteredConfigurableModules = configurableModules.map(module => ({
  name : module.name,
  configurables : module.configurables,
}));

Upvotes: 0

Siddharth Pal
Siddharth Pal

Reputation: 1458

As I see you want to map from one array to another. You can do it in 2 ways:

Inline

  const filteredConfigurableModules = configurableModules.map(module => ({name: module.name, configurables: module.configurables}));

When you do inline and return an object you have to wrap it in parenthesis so that it gets evaluated properly.

Use Return Statement

const filteredConfigurableModules = configurableModules.map(module => {
  return {
    name: module.name,
    configurables: module.configurables
  };
});

Upvotes: 5

Luis Louis
Luis Louis

Reputation: 694

You can create a new object on the arrow function from the map:

const filteredConfigurableModules = configurableModules.map(module =>
  ({ name: module.name, configurables: module.configurables })
);

this return an array of objects with name and module fields.

If you return an object, you need to use parenthesis because otherwise it will be treated as a code body with no return.

Upvotes: 0

Related Questions