如果我知道一個物件存在于具有唯一鍵:值對的陣列中,我是否可以使用 .find() 來獲取該物件,或者是否有一種不需要迭代的方法?
鑒于:
const testObj = [
{id: '001', first: 'fThing1', other: [{id: '001.1'}, {id: '001.2'}], arr: ['a1', 'b1', 'c1'] },
{id: '002', first: 'fThing2', other: [{id: '002.1'}, {id: '002.2'}], arr: ['a2', 'b2', 'c2'] },
{id: '003', first: 'fThing3', other: [{id: '003.1'}, {id: '003.2'}], arr: ['a3', 'b3', 'c3'] }
]
是否有一個符號要做:
testObj.id['001'](some notation)first = 'something'
或者我必須這樣做:
temp = testObj.find(to => to.id === '001')
temp.first = 'something'
uj5u.com熱心網友回復:
直接回答你的問題...
是否有符號要做
答案是“不”。
如果您的元素具有唯一的 ID,請考慮將它們收集到一個Map 中,id如果您需要這種訪問...
const testObj = [{"id":"001","first":"fThing1","other":[{"id":"001.1"},{"id":"001.2"}],"arr":["a1","b1","c1"]},{"id":"002","first":"fThing2","other":[{"id":"002.1"},{"id":"002.2"}],"arr":["a2","b2","c2"]},{"id":"003","first":"fThing3","other":[{"id":"003.1"},{"id":"003.2"}],"arr":["a3","b3","c3"]}]
const idMap = new Map(testObj.map(o => [o.id, o]))
// word of warning, this will error if the ID doesn't exist
idMap.get("001").first = "something"
console.log(testObj[0])
.as-console-wrapper { max-height: 100% !important; }
因為在物件參考testObj和Map是相同的,一個任何更改將反映在其他。
uj5u.com熱心網友回復:
正如@Phil 所提到的,您詢問的符號是不可能的。
另一種選擇是使用函式.map()回傳一個包含更新物件的新陣列:
const testObj = [
{id: '001', first: 'fThing1', other: [{id: '001.1'}, {id: '001.2'}], arr: ['a1', 'b1', 'c1'] },
{id: '002', first: 'fThing2', other: [{id: '002.1'}, {id: '002.2'}], arr: ['a2', 'b2', 'c2'] },
{id: '003', first: 'fThing3', other: [{id: '003.1'}, {id: '003.2'}], arr: ['a3', 'b3', 'c3'] }
];
const result = testObj.map(item =>
item.id === '001' ? {
...item,
first: 'something'
} : item
);
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/335747.html
標籤:javascript 数组 目的 ecmascript-6
上一篇:具有多個條件的物件中的過濾器陣列
