If I know an object exists in an array with a unique key:value pair do I have use .find() to get the object or is there a way that doesn’t require iteration?
Given:
JavaScript
x
6
1
const testObj = [
2
{id: '001', first: 'fThing1', other: [{id: '001.1'}, {id: '001.2'}], arr: ['a1', 'b1', 'c1'] },
3
{id: '002', first: 'fThing2', other: [{id: '002.1'}, {id: '002.2'}], arr: ['a2', 'b2', 'c2'] },
4
{id: '003', first: 'fThing3', other: [{id: '003.1'}, {id: '003.2'}], arr: ['a3', 'b3', 'c3'] }
5
]
6
Is there a notation to do:
JavaScript
1
2
1
testObj.id['001'](some notation)first = 'something'
2
Or do I have to do:
JavaScript
1
3
1
temp = testObj.find(to => to.id === '001')
2
temp.first = 'something'
3
Advertisement
Answer
To directly answer your question…
Is there a notation to do
The answer is “no”.
If your elements have unique IDs, considering collecting them into a Map keyed by id
if you need that sort of access…
JavaScript
1
8
1
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"]}]
2
3
const idMap = new Map(testObj.map(o => [o.id, o]))
4
5
// word of warning, this will error if the ID doesn't exist
6
idMap.get("001").first = "something"
7
8
console.log(testObj[0])
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; }
Because the object references in testObj
and the Map
are the same, any changes to one will be reflected in the other.