javascript - 给定不同的唯一键:值,是否可以使用“=”设置一个对象属性?
问题描述
如果我知道一个对象存在于具有唯一键:值对的数组中,我是否使用 .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,请考虑将它们收集到一个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
是相同的,所以对其中一个的任何更改都将反映在另一个中。
推荐阅读
- scala - 有没有办法使用 Akka Stash 而不是优先邮箱?
- windows - Tensorflow 找不到 DLL,但 DLL 目录在 PATH 中
- reactjs - 表单文本字段更新
- javascript - 使用刀片中的参数调用 javascript 函数
- android - 如何隐藏正在播放的视频 Youtube player api android
- laravel - Laravel中有多行时如何更新行
- javascript - AngularJS-MVVM-绑定视图和模型(范围)的问题
- c# - HTTPWebRequest 未添加 Accept 标头
- c++ - 如何在类上下文中使用 fcntl.h 库?
- java - 整数类型中的 parseInt() 方法不适用于 Action Listener (Java) 中的参数 (JTextField)