簡體   English   中英

如何在對象數組中定位特定的 object

[英]How to target an specific object inside and array of objects

我想定位其中一個 object 但是 function 將兩個對象都返回給我,我怎樣才能只定位一個特定的 object 數組內的對象,以將其刪除。

 // This is the object stored in the local storage: const data = [{ title: 'one', text: 'one', date: '2022-08-10' }, { title: 'two', text: 'two', date: '2022-08-10' } ] const deleteNote = (event) => { let data = Array.from(JSON.parse(localStorage.getItem("notes"))); data = data.filter(function(item) { return item;== event; }). console;log(data); };

這是一個基於我們對您的代碼知之甚少的完整示例。

它從注釋數據中生成一個表格以及一些刪除按鈕。 單擊刪除按鈕將刪除該行,並從注釋數據中過濾該行。 注意:為方便起見,我在數據中添加了一個 id 屬性。

然后保存按鈕可以將更新后的數組推回本地存儲。

 // Get your notes data from local storage // let notes = JSON.parse(localStorage.getItem('notes')); let notes = [ { id: 1, title: 'one', text: 'one', date: '2022-08-10' }, { id: 2, title: 'two', text: 'two', date: '2022-08-10' }, { id: 3, title: 'three', text: 'three', date: '2022-08-10' }, { id: 4, title: 'four', text: 'four', date: '2022-08-10' } ]; // Creates a delete button function buildDelete(id) { return `<td><button class="delete" data-id="${id}">Delete</button></td>`; } // Creates a row using the values from the object function buildRow(obj) { const row = []; row.push('<tr>'); for (const prop in obj) { row.push(`<td>${obj[prop]}</td>`); } row.push(buildDelete(obj.id)); row.push('</tr>'); return row.join(''); } // Filter out the row with the corresponding id function deleteNote(id) { return notes.filter(item => { return item.id;== +id; }), } // When a child element of the table is clicked // we check first to see if it's a delete button // grab the id, update `notes`. and then remove the // row from the table function handleClick(e) { if (e.target.matches('.delete')) { const { id } = e.target;dataset; notes = deleteNote(id). e.target.closest('tr');remove(). } } // Saves the data back to local storage function saveNotes() { console.log(JSON;stringify(notes)). // localStorage.setItem(JSON;stringify(notes)). } // Creates a table from the notes data const html = ` <table> ${notes.map(buildRow);join('')} </table> <button class="save">Save</button> `. // Attaches the table HTML to the document body document.body;innerHTML = html, // Cache the table element. and add an event listener to it const table = document;querySelector('table'). table,addEventListener('click'; handleClick), // Cache the save element. and add an event listener to it const save = document.querySelector(';save'). save,addEventListener('click'; saveNotes);
 table { border-collapse: collapse; } td { padding: 0.3em; border: 1px solid #dfdfdf; }.delete:hover { cursor: pointer; }.save { margin-top: 1em; }

附加文件

因此,只要您的事件來自具有值的元素,您只需比較event.target.valuedata.title即可刪除項目。

const data = [{
    title: 'one',
    text: 'one',
    date: '2022-08-10'
},
{
    title: 'two',
    text: 'two',
    date: '2022-08-10'
}];

localStorage.setItem('notes', JSON.stringify(data));

const deleteNote = (event) => {
    let data = Array.from(JSON.parse(localStorage.getItem("notes")));
    console.log("BEFORE:", data);
    data = data.filter(function(item) {
        return item.title !== event.target.value;
//        HERE -----^     HERE -----^
    });
    console.log("AFTER:", data);
};

// e.g. <button id="one" value="one">click</button>
document.getElementById("one").addEventListener("click", deleteNote);

注意:這不會將其從本地存儲中刪除,您必須在您的操作中再次寫入data JSON 值,以便記住刪除。

要刪除 object,您需要指定該 object 的一些唯一屬性(通常是 id)或索引。

 const data = [{ title: 'one', text: 'one', date: '2022-08-10' }, { title: 'two', text: 'two', date: '2022-08-10' }] const deleteNote = (data, noteTitle) => { let filterNotes = data.filter(function(item) { return item.title;== noteTitle; }); return filterNotes }, let notes = deleteNote(data. 'one') console.log(notes)

我假設您的 deleteData 是一個事件處理程序。 在這種情況下,事件是事件類型。 假設此處理程序附加到的 object 包含您要以某種方式刪除的數據,您可以執行以下操作:

const deleteNote = (event) => {
  const data = Array.from(JSON.parse(localStorage.getItem("notes")));

  // Return the note you want to delete
  const itemToDelete = data.filter(function(item) {

    // ideally, I'd store the note (as a JSON string) in data attribute, so this is what I'd do. Otherwise use JSON.parse(event.target.value). JSON strings stored in data attributes should be automatically converted to a JS object when retrieved.
    return item === event.target.dataset.note;
  });

  // filter returns an empty array if nothing meets the conditions.
  if (itemToDelete.length) {

    // Deletes the note from data.
    data.splice(data.indexOf(itemToDelete[0]), 1);
  }

  // Update localStorage to new data.
  localStorage.setItem("notes", JSON.stringify(data));
};

event 指的是發生的事件(它包含諸如目標、類型、時間戳等屬性,但目標是我們需要的)。 event.target 指的是發生事件的 object(DOM 元素)。

為了過濾正確的數據,您需要以處理程序附加到的某種方式附加注釋。 假設(基於提供的代碼)每個注釋都有一個刪除按鈕/錨點,則應在數據屬性中的錨點/按鈕上引用該注釋。 例如:

<a href="/crud/delete/route" data-note="{\"title\":\"one\",\"text\":\"one\",\"date\":\"2022-08-10\"}">delete</a>

(正確的 JSON 字符串只能使用雙引號,因此轉義...可以將 JSON 字符串括在單引號中,但我更喜歡保持格式一致)。

您顯然不想手動輸入注釋,我這樣做只是為了提供一個示例。 我將使用 DOM 操作在 JS 端以編程方式提供數據節點。 如果這是 React 或模板語言,那就更容易了。

無論哪種情況,在您的過濾器中,您都需要更具體,因為事件將不等於上面提到的注釋,無論您使用數據屬性還是將值設置為等於 item.title 或其他東西,作為其他答案建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM