Javascript-将1转换为true(带有示例)

时间:2018-07-04 10:12:39

标签: javascript json

我有一个JSON,如果值是1,我想将FUTURE_CALL转换为true,0则返回false。

我该怎么做?我的示例不起作用。

var tickets = '{tickets: {
   "Tickets": [
      {
         "TICKET_ID": "",
         "TITLE": "",
         "DESCRIPTION": "",
         "CREATION_DATE": "",
         "COMPLETION_DATE": "",
         "CREATED_BY": "",
         "FUTURE_CALL": "",
         "TICKET_PRIORITY_DESCRIPTION": "",
         "TICKET_PRIORITY_CODE": "",
         "TICKET_CATEGORY_DESCRIPTION": "",
         "TICKET_CATEGORY_CODE": "",
         "TICKET_TYPE_CODE": "",
         "TICKET_TYPE_DESCRIPTION": "",
         "TICKET_TAG_CODE": "",
         "TICKET_TAG_DESCRIPTION": "",
         "TICKET_STATUS_CODE": "",
         "TICKET_STATUS_DESCRIPTION": "",
         "DUE_DATE": "",
         "ACCOUNT_ID": ""
      }
   ]
}}';

var updatedTickets = tickets;
for(var i = 0; i < updatedTickets.tickets['Tickets'].length; i++) {
     if(updatedTickets[i].tickets['Tickets'].FUTURE_CALL == 1) {
        updatedTickets[i].tickets['Tickets'].FUTURE_CALL = true;
     }
}

2 个答案:

答案 0 :(得分:2)

首先,您的代码中存在一个小问题:

updatedTickets[i].tickets['Tickets']

updatedTiclets是一个对象,其tickets['Tickets"]是一个数组,因此您必须:

updatedTickets.tickets['Tickets'][i]

然后您的比较应该可以进行,但是最简单的方法就是将其转换为数字:

if( +updatedTickets.tickets['Tickets'][i].FUTURE_CALL)

这将起作用,因为0是虚假的,而1是真实的。

var updatedTickets = tickets;
for(const ticket of updatedTickets.tickets['Tickets']) k
 ticket.FUTURE_CALL =
     ticket.FUTURE_CALL === "1";        
}

答案 1 :(得分:0)

  1. 起初,您没有验证JSON –必须编写{"tickets":而不是{tickets:(就像您的代码一样)。

  2. 然后,您必须使用JSON.parse来解析JSON。

  3. 然后,如果要在一个字符串中写入反斜杠,则必须在JSON字符串的每一行中使用反斜杠。

  4. updatedTickets[i].tickets['Tickets']是错误的。您必须写updatedTickets.tickets['Tickets'][i]

我更正了您的代码:

var tickets = '{"tickets": {\
    "Tickets": [\
    {\
        "TICKET_ID": "",\
        "TITLE": "",\
        "DESCRIPTION": "",\
        "CREATION_DATE": "",\
        "COMPLETION_DATE": "",\
        "CREATED_BY": "",\
        "FUTURE_CALL": "",\
        "TICKET_PRIORITY_DESCRIPTION": "",\
        "TICKET_PRIORITY_CODE": "",\
        "TICKET_CATEGORY_DESCRIPTION": "",\
        "TICKET_CATEGORY_CODE": "",\
        "TICKET_TYPE_CODE": "",\
        "TICKET_TYPE_DESCRIPTION": "",\
        "TICKET_TAG_CODE": "",\
        "TICKET_TAG_DESCRIPTION": "",\
        "TICKET_STATUS_CODE": "",\
        "TICKET_STATUS_DESCRIPTION": "",\
        "DUE_DATE": "",\
        "ACCOUNT_ID": ""\
    }]\
}}';

var updatedTickets = JSON.parse(tickets),
	ticketsObj = updatedTickets.tickets['Tickets'];

for(var i = 0; i < ticketsObj.length; i++)
    // symbol "+" convert string to integer
	ticketsObj[i].FUTURE_CALL = +ticketsObj[i].FUTURE_CALL == 1 ? true : false;

console.log(JSON.stringify(updatedTickets, null, '\t'));