Array of Objects vs Nested Object?

后端 未结 2 951
再見小時候
再見小時候 2020-12-31 09:35

I have a very basic programing question that i hoped you can shed a light on.

I am working a lot of objects right now and i was wondering if it is better to search f

相关标签:
2条回答
  • Understanding Objects vs Arrays and When to Use Them

    • What are Objects and how do they differ from Arrays in Javascript?
    • When is it advantageous to use one over the other?

    Arrays: Arrays come with several, very useful native methods. We can add a new element to existing array instance using push() and remove the last element from the array via pop(). We can also use splice() to remove n elements and/or insert new element(s) at index i.

    Object: Think about objects as associative arrays, i.e. list of key -> value pairs. These keys are referred to as object properties.

    Checking if Property or Value Exists

    Arrays: Generally when we work with arrays, we care less about indexes and more about values. One of the common operations we perform with Arrays is checking if a certain value is in the array. This is easily accomplished using indexOf() method.

    Object: In contrast to Arrays, we generally want to know if an Object contains a certain property. Usually we will write a function that takes Object as an argument and will expect that it contains a certain set of properties. This Object can come from an API or some other piece of code and we shouldn't rely on it having all the properties we expect. It is always a good idea to check whether the property exists before accessing the value behind that property. Objects come with hasOwnProperty() method which allows us to do just that.

    extracted from here

    0 讨论(0)
  • 2020-12-31 09:45

    It's a kind of question with no wrong answers. Both cases are good enough. Depends on case. You should think about the semantics. Do you return array of elements (i.e. list of users, etc.) or just object with a lot of properties within? This structure should depend on data, I guess. But keep in mind, that access by property object.property is faster than array[index].

    0 讨论(0)
提交回复
热议问题