D Durham
D Durham

Reputation: 1341

JS conditional ES6 map

We've found examples here of returning maps for ES6 arrays of primitives with conditionals, but we need same for an array of objects.

The source array has a topic.id, topic.name, and topic.parent_id:

topics: [
  {id: 1, name: 'test_1', parent_id 0},
  {id: 2, name: 'test_2', parent_id 0},
  {id: 1, name: 'test_child_1', parent_id 1}
]

We need to return an array of objects where the topic_id is now key 'value', and the topic.name is now key 'label' with the value having 2 non-breaking spaces appended to the beginning of it IF the topic.parent_id > 0. So for the data above, we'd like to get back:

[
  {value: 1, label: 'test_1'},
  {value: 2, label: 'test_2'},
  {value: 3, label: '  test_child_1'}
]

We've tried a buch of IF's, ternaries (like the one below), but can't quite seem to nail a syntax for this that works.

 let test ="topics.map(topic => (
  {
    label: topic.parent_id > 0 : '  ' + topic.name ? topic.name,
    value: topic.id,
  } 
))"

Any help is appreciated!

Upvotes: 0

Views: 908

Answers (2)

Naim Sulejmani
Naim Sulejmani

Reputation: 1120

This as simple solution you can do as follows

var labelValues =topics.map((topic)=> ({
    label: topic.parent_id > 0 ? '  ' + topic.name : topic.name,
    value: topic.id 
}));

Upvotes: 2

Ibu
Ibu

Reputation: 43810

You can use the map function this way:

let test = topics.map(function(topic){
    return {
      label:topic.parent_id > 0? '  ' + topic.name : topic.name,
      value: topic.id
    };
});

Update: Now that I take a good look at it, I see that you made a mistake in your tertiary operation. You reversed the position of the ? and the :. And you added double quotes so it is read as a string. Update it to this:

let test = topics.map(topic => (
  {
    label: topic.parent_id > 0 ? '  ' + topic.name : topic.name,
    value: topic.id,
  } 
));

Upvotes: 3

Related Questions