简体   繁体   English

如何使用 jQuery 通过键删除 JSON 中的 JSON?

[英]How can I remove a JSON inside a JSON by a key using jQuery?

I have the following JSON structure:我有以下 JSON 结构:

[
    {"key":1,"idProduct":"Monitor","obsProduct":""},
    {"key":2,"idProduct":"Mouse","obsProduct":""},
    {"key":3,"idProduct":"Keyboard","obsProduct":""},
    {"key":4,"idProduct":"Processor","obsProduct":""}
]

And the following HTML table (representing the JSON):以及以下 HTML 表(代表 JSON):

在此处输入图片说明

When user click on "Remove" button , I need to remove the corresponding iten on JSON.当用户单击“删除” button ,我需要删除 JSON 上的相应项目。 When user click, I can capture the key , so I need to remove iten using the key value.当用户单击时,我可以捕获key ,因此我需要使用key值删除 iten。

Assuming that the user click on "Remove" button on "Mouse", so, the JSON needs to return that way:假设用户单击“鼠标”上的“删除” button ,那么 JSON 需要以这种方式返回:

[
    {"key":1,"idProduct":"Monitor","obsProduct":""},
    {"key":3,"idProduct":"Keyboard","obsProduct":""},
    {"key":4,"idProduct":"Processor","obsProduct":""}
]

How can I do this?我怎样才能做到这一点?

HTML of table:表格的 HTML:

<div class="row">
    <div class="col-md-12">
        <div class="table-responsive">
            <table class="table table-bordered table-hover" id="table-products">
            <thead style="background-color: #f2f2f2">
                <tr class="text-center">
                    <th style="width: 40%">Product</th>                     
                    <th style="width: 40%">Obs</th>
                    <th style="width: 20%">Action</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td colspan="3">No iten!</td>
                </tr>
                <!-- Will be generated! -->
            </tbody>
        </table>
        </div>
    </div>
</div>

JS that generates the lines:生成行的JS:

var i = 1;
var itensArray = [];
var nameProduct = $("input[name='nameProd']").val();
var obsProduct = $("input[name='obsProd']").val();

if(i <= 5)
{
    var newItem = '<tr class="itemRow"><td>' + nameProduct + '</td><td>' + obsProduct + '</td><td><button type="button" name="' + i + '" class="btn btn-outline-danger btn-sm" id="btnRemoveProduct"><i class="far fa-trash-alt"></i> Remove</button></td></tr>';
    if(i == 1) 
        $("#table-products tbody").html(newItem); 
    else
        $("#table-products tbody").append(newItem);

    var products = {
        key: i,
        idProduct: nameProduct,
        obsProduct: obsProduct
    };
    itensArray.push(products)
    var aux = JSON.stringify(itensArray);
    i++;
    console.log(aux);
}

JS that remove lines from table:从表中删除行的 JS:

$("#table-products").on('click', '#btnRemoveItem', function(){
    var idProduct = $(this).attr("name");
    $(this).closest('tr').remove();
    toastr.success('Iten removed!');
    i--;
    if(i == 1)
    {
        var defaultItem = '<tr><td colspan="3">No iten added!</td></tr>';
        $("#table-products tbody").html(defaultItem);
    }

    /* I NEED TO PUT HERE THE CODE TO REMOVE ITEM FROM JSON */
});

Iterating through the array of objects and finding the matching object having key as the key value which is captured when clicking on remove button.遍历对象数组并找到匹配对象,该对象具有键作为单击删除按钮时捕获的键值。

 var itensArray = [ {"key":1,"idProduct":"Monitor","obsProduct":""}, {"key":2,"idProduct":"Mouse","obsProduct":""}, {"key":3,"idProduct":"Keyboard","obsProduct":""}, {"key":4,"idProduct":"Processor","obsProduct":""} ]; //key is captured in a variable on click of remove button. var idProduct = 2; for (var i = 0; i < itensArray.length; i++) { var obj = itensArray[i]; if (obj.key === idProduct) { itensArray.splice(i, 1); } } console.log(itensArray);

The simplest way is to assing some id to button which responds entry id.最简单的方法是将一些 id 分配给响应条目 id 的按钮。 While delete button is clicked you can extract ID from button and you know which row to delete.单击删除按钮时,您可以从按钮中提取 ID,并且您知道要删除哪一行。

You said you can capture the key, so I'm assuming you've got some kind of click handler function that's receiving that key.你说你可以捕获密钥,所以我假设你有某种接收该密钥的点击处理函数。 From there the best way to do it is probably to create a new array that filters out the element that matches, and replace the old array with the new.从那里最好的方法可能是创建一个新数组,过滤掉匹配的元素,并用新数组替换旧数组。 (Generally considered a better practice than mutating the array in place with something like .splice) (通常被认为比使用 .splice 之类的东西改变数组更好的做法)

const capturedKey = event.target.value // or however you're capturing it
yourArray = yourArray.filter(obj => obj.key !== capturedKey)

You can find the index using Array.findIndex (It will return on the first match so it is an optimized way if your 'key' values are unique)您可以使用Array.findIndex找到索引(它将在第一次匹配时返回,因此如果您的“键”值是唯一的,它是一种优化方式)

 const myArray = [ {"key":1,"idProduct":"Monitor","obsProduct":""}, {"key":2,"idProduct":"Mouse","obsProduct":""}, {"key":3,"idProduct":"Keyboard","obsProduct":""}, {"key":4,"idProduct":"Processor","obsProduct":""} ]; const idToDelete = 2; // retrieved via clicked btn const idx = myArray.findIndex( item => item.key == idToDelete ); if(idx != -1) { myArray.splice(idx, 1); } console.log(myArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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