-2

Here's an obj.

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

Here's object arraies.

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, ...]
} 

I'd like to find a class in the school. School is only one. And Class, Person are multiple.

And I'd like to add, remove, edit school it belongs to and the class.

Is there any way to find an object with an index? I mean like a HashMap. You access a value with a string like this.

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

I can find the object with for loop but, the login seems very complicated and not efficient as much as O(n^2).

Edit

I'd like to accomplish get, put, remove, edit in an array with Object.

For example,

I want to remove person3. Then, I can find its class like this.

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

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

It will find the item in O(n).

Community
  • 1
  • 1
c-an
  • 3,543
  • 5
  • 35
  • 82

1 Answers1

0

If you want a specific functionality, I would create a function for it. For example you can create removeClub function and putClub function:

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);
wakakak
  • 842
  • 5
  • 13
  • Is there no way to do it in `O(1)`? – c-an Oct 11 '19 at 04:56
  • I tried this method and I don't know if an object works as well. I did `slice(index, 1)` to remove the Object element and It is not removed. – c-an Oct 14 '19 at 03:13