我们在这里找到了使用条件返回 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 现在是键“value”,而 topic.name 现在是键“label”,并且该值的开头附加了 2 个不间断空格(如果主题) .parent_id > 0。因此对于上面的数据,我们想返回:
[
{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,
}
));
关于javascript - JS 条件 ES6 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52021591/