如果我知道一个对象存在于一个具有唯一键:值对的数组中,我可以使用.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'
要直接回答您的问题。。。
有符号可以进行吗
答案是"否">。
如果你的元素有唯一的ID,如果你需要这种访问,可以考虑将它们收集到一个由id
键控的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 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
中的对象引用是相同的,所以对其中一个的任何更改都将反映在另一个中。
正如@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);