对象VS嵌套对象的数组? [英] Array of Objects vs Nested Object?

查看:75
本文介绍了对象VS嵌套对象的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我希望你可以摆脱一盏灯一个非常基本的编程问题。

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 for content inside an array of objects or inside a nested object?

有关例如,我可以在同一个数据样本存储在以下两个方面:

For eg, i can store the same data sample in the following two ways:

data1 = [ 
{ "id":1, "key1: "value1", "key2:"value2"},
{ "id":2, "key1: "value1", "key2:"value2"},
{ "id":3, "key1: "value1", "key2:"value2"},
{ "id":4, "key1: "value1", "key2:"value2"},
.....
]

data2 = {
"id_1": { "key1: "value1", "key2:"value2"},
"id_2": { "key1: "value1", "key2:"value2"},
"id_3": { "key1: "value1", "key2:"value2"},
"id_4": { "key1: "value1", "key2:"value2"},
.....
}

现在的要求是从一个子对象目标属性。而我们所知道的是与它相关的ID(而不是索引)。

Now the requirement is to get a certain property from a child object. And all we know is the id (and not the index) associated with it.

如果我是使用数组的方法,我将不得不使用循环和过滤器阵列中的各个对象访问任何内容/值。这种方法似乎相当麻烦是,通过各个子对象迭代感觉非常低效的给我。然而,每当我看到类似的数据样本是由有经验的程序员来实现,它们似乎都使用数组了不少。

If i were to use the array method, i will have to use loops and array filters to access any content/value in the individual objects. This method seems rather cumbersome to be and iterating through each child object feels very inefficient to me. Yet whenever i see similar data samples being implemented by experienced programmers, they all seem to using arrays a lot.

如果我是使用嵌套对象的方法,我所要做的就是调用 data2.id_2.key2 来获取特定的值。

If I were to use the nested object method, all i have to do is call data2.id_2.key2 to get that specific value.

这是做事的推荐的方法?我将相当大的数据集被打,因此,选项将有更好的表现?

Which is the recommended way of doing things? I will be playing with rather large datasets and so, option will have better performance?

推荐答案

这是一个样的问题,没有错误的答案。这两种情况都不够好。要看情况。你应该考虑的语义。你返回元素的数组(即用户列表等),或者只是在很多的属性对象呢?这种结构应该依赖于数据,我猜。
但请记住,通过属性,访问 object.property 快于数组[索引]

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

这篇关于对象VS嵌套对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆