首页 > 解决方案 > 对象数组:建议通过对象键或数组索引或数组项本身选择特定项目?

问题描述

我正在处理一个[]类对象数组。要求是使用该对象数组来记住当前选定的对象。例如,我有一个名为 的类Person,它contactsvar obj = new Person(); contacts.push(obj);

class Person(){
   // props, constructors and methods 
}

const contacts = [new Person(0), new Person(1), new Person(2), new Person(3)]

var selectedPerson;

所以我希望用户personcontact列表中选择任何,所以我正在使用<select>并且<option>用户允许选择任何Person这意味着我正在使用name道具,所以当用户选择或做任何事情时,我现在从用户选择中Person获取需要与's 的对象交互或使用它为用户进行少量计算并显示结果。namePersonPerson

我可以onChange<select>


onChange(e){
   // store the value and filter it out to get the Person object when need calculation
   selectedPerson = e.target.value
   // store the contact item which is person object and use them everywhere
   selectedPerson = contacts.find((person)=> person.name===e.targe.value)
}
// multiple use of the selectedPerson

哪种方法更好,为什么?

有没有其他方法可以更有效地实现同样的目标?

请分享关于该问题未正确提出的想法。

标签: javascriptarraysobject

解决方案


你所做的很好,只要在对象name数组中是独一无二的,Person并且数组不是真正的大(如果它被输入option元素就不会)。如果数组内容发生变化,使用name而不是数组索引也更健壮。

您可以考虑使用 aMap而不是数组:

const contacts = new Map();
function addContact(person) {
    // If you want proactive notification of *replacing* a person, uncomment:
    // if (contacts.has(person.name)) {
    //     throw new Error(`contacts map already contains a person named ${person.name}`);
    // }
    contacts.set(person.name, person);
}
addContact(new Person(0));
addContact(new Person(1));
// ...

然后在onChange

onChange(e) {
    const person = contacts.get(e.target.value);
    // ...
}

这只是比数组扫描更有效的检索(但这与您将在元素中呈现的人数无关option),并且对我来说,语义上更适合操作 - 没有机会的重复名称。如果您需要遍历映射中的条目(按添加顺序),映射是可迭代的:

for (const person of contacts.values()) {
    // ...
}

推荐阅读