0

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!

1
  • 2
    test is a string? Commented Aug 25, 2018 at 22:09

2 Answers 2

3

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,
  } 
));
Sign up to request clarification or add additional context in comments.

Comments

2

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 
}));

1 Comment

The control we are passing it to trims the label, but add the non-breaking spaces works perfectly. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.