简体   繁体   English

JS条件ES6地图

[英]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. 我们在这里找到了一些示例,这些示例返回带有条件的基本元素的ES6数组的映射,但是对于对象数组,我们需要相同的映射。

The source array has a topic.id, topic.name, and topic.parent_id: 源数组具有topic.id,topic.name和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: 我们需要返回一个对象数组,其中topic_id现在是键“值”,而topic.name现在是键“标签”,如果topic.parent_id>,则该值在其开头附加2个不间断空格。 0.所以对于上面的数据,我们想回来:

[
  {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. 我们已经尝试了很多IF的三进制(例如下面的IF),但是似乎并不能确定一个可行的语法。

 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: 您可以通过以下方式使用map函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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