首页 > 解决方案 > 给定不同的唯一键:值,是否可以使用“=”设置一个对象属性?

问题描述

如果我知道一个对象存在于具有唯一键:值对的数组中,我是否使用 .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'

标签: javascriptarraysobjectecmascript-6

解决方案


直接回答你的问题...

有没有符号可以做

答案是“不”

如果您的元素具有唯一的 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是相同的,所以对其中一个的任何更改都将反映在另一个中。


推荐阅读