简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM