给定不同的唯一性 key:value,'=' 能否用于设置一个对象 属性?

Can '=' be used to set one object property given a different unique key:value?

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

直接回答你的问题...

Is there a notation to do

答案是“否”

如果您的元素具有唯一 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; }

因为 testObjMap 中的对象引用是相同的,所以对一个的任何更改都会反映在另一个中。

@Phil所述,您所询问的符号是不可能的。

另一种选择是使用函数 .map() 来 return 一个包含更新对象的新数组:

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);