我试图将结果作为数据列表下拉列表中的选项添加到对象中,并且可以正常工作,但问题是并非所有元素始终在对象中都具有一定级别,这会影响将结果添加到列表中。
$("#returnedProducts").append($("<option/>",
{
"srindex": i,
"data-details": JSON.stringify(result[i]._source.name.family),
//I want to say if result[i]._source.fabric exists, then do this next line else, just move to "value"
"data-fabric":JSON.stringify(result[i]._source.fabric[1]),
"value": result[i]._source.category,
"html": result[i]._source.category,
}
));
我该如何说“只有在result [i] ._ source.fabric存在的情况下才设置数据结构,否则不进行设置并移至“值”?
答案 0 :(得分:3)
使用三元运算符:
{
"srindex": i,
"data-details": JSON.stringify(result[i]._source.name.family),
"data-fabric": result[i]._source.fabric ? JSON.stringify(result[i]._source.fabric[1]) : undefined,
"value": result[i]._source.category,
"html": result[i]._source.category,
}
让我知道是否需要进一步澄清
答案 1 :(得分:2)
您实际上不能在对象初始化器中执行类似的操作,但是如果将选项对象组合到函数中,则可以轻松实现:
ipv4_public.20180828