Javascript JS条件ES6映射

Javascript JS条件ES6映射,javascript,arrays,Javascript,Arrays,我们在这里找到了一些示例,可以返回带有条件的ES6原语数组的映射,但是对于对象数组,我们需要相同的映射 源数组具有topic.id、topic.name和topic.parent\u 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} ] 我们需要返回一个对象数组,其中t

我们在这里找到了一些示例,可以返回带有条件的ES6原语数组的映射,但是对于对象数组,我们需要相同的映射

源数组具有topic.id、topic.name和topic.parent\u 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}
]
我们需要返回一个对象数组,其中topic\u id现在是key“value”,topic.name现在是key“label”,如果topic.parent\u id>0,则该值的开头会附加两个非中断空格。因此,对于上述数据,我们想返回:

[
  {value: 1, label: 'test_1'},
  {value: 2, label: 'test_2'},
  {value: 3, label: '  test_child_1'}
]
我们已经尝试了一些IF's,ternaries(如下面的一个),但似乎还不能确定一个有效的语法

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

感谢您的帮助

您可以通过以下方式使用映射功能:

let test = topics.map(function(topic){
    return {
      label:topic.parent_id > 0? '  ' + topic.name : topic.name,
      value: topic.id
    };
});
更新: 现在我仔细看了一下,我发现你在第三次手术中犯了一个错误。您颠倒了
的位置。您添加了双引号,因此它被读取为字符串。将其更新为:

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

可以通过以下方式使用映射功能:

let test = topics.map(function(topic){
    return {
      label:topic.parent_id > 0? '  ' + topic.name : topic.name,
      value: topic.id
    };
});
更新: 现在我仔细看了一下,我发现你在第三次手术中犯了一个错误。您颠倒了
的位置。您添加了双引号,因此它被读取为字符串。将其更新为:

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

这是一个简单的解决方案,您可以执行以下操作

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

这是一个简单的解决方案,您可以执行以下操作

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

test是一个字符串?test是一个字符串?我们传递给它的控件会修剪标签,但添加不间断空格的效果非常好。谢谢我们传递给它的控件会修剪标签,但添加非打断空格的效果非常好。谢谢