multiple objects with the same key

2019-08-19 18:50发布

问题:

I have an array of objects:

[object, object, object, object, object]

that i want to set a key to each using the object title:

{test:object, tester:object, foo:object, bar:object, test:object}

so i could say array.test instead of having to do array[0].title. However the key can be generic, and when there are multiple objects with the same key it replaces the original.

Is what i want to do impossible without adding an index value to the key? In which case is the tidiest solution what i originally had array[0].title.

回答1:

is there any way to set the same key to multiple objects without replacing it other than appending an index value to to the key?

No. The object keys are unique, meaning a key can hold only one value. If you like to hold multiple value, then you assign array value to it. like { key : [value1, value2 ...]} but this is of no use for your problem. Also you are not sure what is the key value, and that is the whole objective of the object/map.

is the way im doing it the best way?

Yes. For the problem you mentioned using array data-structure/construct is good.