我有一個看起來像這樣的物件陣列:
const tickets =
[
{
ticketId: 'aaa',
authorId: 'abc',
replyCount: 0,
status: 'Open',
threads: [
{
threadId: 'abc',
authorId: 'abc',
direction: 'in',
content: 'blah blah blahh'
},
],
},
{
ticketId: 'bbb',
authorId: 'efg',
replyCount: 0,
status: 'Open',
threads: [
{
threadId: 'efg',
authorId: 'efg',
direction: 'in',
content: 'blah blah blahh'
},
],
},
.......
]
現在我想訪問ticketIdequals的陣列項aaa并更改它的threads屬性。
我嘗試過使用tickets['aaa'].threads = [ ... ],但它會引發以下錯誤:
埃斯林特:Unsafe member access .threads on an 'any' value
打字稿:Element implicitly has an 'any' type because index expression is not of type 'number'
uj5u.com熱心網友回復:
如果您只是想通過屬性進行變異,您可以使用 indexOf 和 mutate 獲取索引
tickets[tickets.indexOf(ticket => ticket.ticketId === "aaa")].threads = [] //mutate here however you want
uj5u.com熱心網友回復:
我希望以下內容對您有用。
var getItem = id => tickets.find(item => item.ticketId === id);
getItem("aaa"); // {ticketId: 'aaa', authorId: 'abc', replyCount: 0, status: 'Open', threads: Array(1)}
uj5u.com熱心網友回復:
找到ticketId等于“aaa”的索引
tickets[tickets.findIndex(v => v.ticketId === "aaa")].threads = [/* ... */];
使用索引驗證:
const idx = tickets.findIndex(v => v.ticketId === "aaa");
if (idx > -1) tickets[idx].threads = [/* ... */];
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463775.html
標籤:javascript 打字稿
下一篇:在同一y對齊線上設定文本
