我们在这里找到了返回带有条件的 ES6 基元数组的映射的示例,但对于对象数组,我们需要相同的映射。
源数组具有 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}
]
我们需要返回一个对象数组,其中topic_id现在是键"值",而 topic.name 现在是键"标签",如果topic.parent_id> 0,则值的开头附加了 2 个不间断空格。因此,对于上面的数据,我们想返回:
[
{value: 1, label: 'test_1'},
{value: 2, label: 'test_2'},
{value: 3, label: ' test_child_1'}
]
我们已经尝试了大量的IF,三元(如下图(,但似乎无法确定有效的语法。
let test ="topics.map(topic => (
{
label: topic.parent_id > 0 : ' ' + topic.name ? topic.name,
value: topic.id,
}
))"
任何帮助不胜感激!
您可以通过以下方式使用 map 函数:
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
}));