如何在对象数组中找到对象?

时间:2019-10-10 05:31:50

标签: javascript node.js object hashmap

这是一个对象。

var person = {
    no: 4,
    name: "Jack",
    hobbies:["soccer, dancing"],
    club: "lion"
}

这里是物体杂物。

var club = {
    no: 2,
    name: "lion",
    teacher: "Linda",
    num: 24
    students: [person, person2, person3, ...]
}

var school = {
    no: "NW-10",
    name: "The school of Victory",
    address: "23 Vega St. Gorgia, Texas",
    classes: [club, club2, club3, ...]
} 

我想在学校找一堂课。学校只是一所。而班级,人是多重的。

我想添加,删除,编辑它所属的schoolclass

有什么方法可以找到带有索引的对象?我的意思是像HashMap。您可以使用这样的字符串访问值。

var mAge = mPerson["age"];
var mAge = mPerson.age;

我可以找到带有for循环的对象,但是登录似乎非常复杂,效率不如O(n ^ 2)。

编辑

我想用对象数组完成getputremoveedit

例如

我要删除person3。然后,我可以找到这样的类。

school[person.club].remove(); // The club item is removed.

school2[person.club].put(2); // The club item is added after second club object.

它将在O(n)中找到该项目。

1 个答案:

答案 0 :(得分:0)

如果您想要特定的功能,我会为其创建一个功能。例如,您可以创建removeClub函数和putClub函数:

var person = {
    no: 4,
    name: "Jack",
    hobbies:["soccer, dancing"],
    club: "lion"
};

var club = {
    no: 2,
    name: "lion",
    teacher: "Linda",
    num: 24,
    students: [person]
}

var school = {
    no: "NW-10",
    name: "The school of Victory",
    address: "23 Vega St. Gorgia, Texas",
    classes: [club]
};

function removeClub(clubName){
  var clubIndex = school.classes.findIndex(c => c.name === clubName);
  school.classes.splice(clubIndex, 1);
}

function putClub(clubName, index){
  school.classes.splice(index, 0, clubName);
}

removeClub(person.club);
putClub(person.club,0);
console.log(school);