简体   繁体   中英

Change JSON Format in javascript

i recently developed a rest service that accept json data in this format

{
    "foods": "food1, food2, food3",
    "qty": "1,2,3"
}

but my javascript generate this format

["food1","1","food2","2","food3","3"]

i wrote my rest in php

data's are from this table body

<tbody id="tr">
    <tr>
        <td class="data">food1</td>
        <td class="data">1</td>
        <td>
            <div class="col-sm-1">
                <button type="button" class="btn btn-danger removethisfood">-</button>
            </div>
        </td>
    </tr>
    <tr>
        <td class="data">food1</td>
        <td class="data">1</td>
        <td>
            <div class="col-sm-1">
                <button type="button" class="btn btn-danger removethisfood">-</button>
            </div>
        </td>
    </tr>
    <tr>
        <td class="data">food1</td>
        <td class="data">1</td>
        <td>
            <div class="col-sm-1">
                <button type="button" class="btn btn-danger removethisfood">-</button>
            </div>
        </td>
    </tr>
</tbody>

my java script code

var tbl = $('#tr').map(function() {
     return $(this).find('td.data').map(function() {
       return $(this).html();
     }).get();
   }).get();
   console.log(JSON.stringify(tbl));

You can achieve the format required by looping over each tr and adding the text of the relevant td to an array, before building the final object by joining the text of the arrays together, something like this:

var foods = [], qty = [];        
$('tr').each(function() {
    var $row = $(this);
    foods.push($row.find('td:eq(0)').text());
    qty.push($row.find('td:eq(1)').text());
})

var obj = {
    foods: foods.join(','),
    qty: qty.join(',')
};

That said, your JSON format could be improved for clarity and simplicty of serialisation/deserialisation. It would make more sense to send an array with each item contained in an object with the parameters being its name and quantity, like this:

var obj = $('tr').map(function() {
    var $row = $(this);
    return {
        food: $row.find('td:eq(0)').text(),
        qty: $row.find('td:eq(1)').text()
    }
}).get()

This output then looks like this:

[{
    "food": "food1",    
    "qty": "1"
},{
    "food": "food2",
    "qty": "1"
},{
    "food": "food3",
    "qty": "1"
}]

Working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM