用运算符验证jQuery中是否存在数组?

时间:2019-07-01 17:43:34

标签: jquery html

我有一个来自ws的数组响应,并且我正在响应中寻找确切的对象,因此当找不到该对象时,jQuery给我一个错误。我试图用||进行验证和?:运算符,但它不尊重它,并且继续给我错误。

这是我的回复示例:

    [{
        "vehicle_id": 771004720190304,
        "schema_id": 301,
        "language_id": 18,
        "content": "04 mar. 2019"
    },
    {
        "vehicle_id": 771004720190304,
        "schema_id": 601,
        "language_id": 18,
        "content": "Todo terreno  de 5 puertas con distancia corta entre los ejes"
    },
    {
        "vehicle_id": 771004720190304,
        "schema_id": 701,
        "language_id": 18,
        "content": "Capacidad para siete pasajeros"
    },
    {
        "vehicle_id": 771004720190304,
        "schema_id": 1101,
        "language_id": 18,
        "content": "16 bocinas BOSE, subwoofer y sonido envolvente"
    },
    {
        "vehicle_id": 771004720190304,
        "schema_id": 1301,
        "language_id": 18,
        "content": "AM/FM, Audífonos Inalámbricos, pantalla táctil y pantalla a color"
    }]

我正在像这样查看数组内部:
第一次尝试

table.append(
  $("<tr>")
           .append(
                '<td><input type="checkbox" checked></td>'+
                '<td>Body style</td>'+
                '<td>'+ response.find(characteristic => characteristic.schema_id == 601 ).content || " " +'</td>'
            ),

第二次尝试

table.append(
$("<tr>")
  .append(
         '<td><input type="checkbox" checked></td>'+
         '<td>Body style</td>'+
         '<td>'+ response.find(characteristic => characteristic.schema_id == 601 ).content ? response.find(characteristic => characteristic.schema_id == 601 ).content : " " +'</td>'
),

当找不到对象时,我希望td中为空值,但是我给出了一个错误,并且该表为空。

1 个答案:

答案 0 :(得分:-3)

使用查找,然后检查匹配项:

response = [{
    "vehicle_id": 771004720190304,
    "schema_id": 301,
    "language_id": 18,
    "content": "04 mar. 2019"
  },
  {
    "vehicle_id": 771004720190304,
    "schema_id": 601,
    "language_id": 18,
    "content": "Todo terreno  de 5 puertas con distancia corta entre los ejes"
  },
  {
    "vehicle_id": 771004720190304,
    "schema_id": 701,
    "language_id": 18,
    "content": "Capacidad para siete pasajeros"
  },
];

table = $('table');
for (e of [701, 401]) {
  let item = response.find(({ schema_id }) => schema_id == e);
  table.append(
    $("<tr>")
    .append(
      '<td><input type="checkbox" checked></td>' +
      '<td>Body style</td>' +
      '<td>' + (item ? item.content : '') + '</td>'
    ),
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
</table>