简体   繁体   English

在JS对象数组中,我应该使用键来标识每个对象吗?

[英]In a JS array of objects, should I use a keys to identify each object?

I'm still learning javascript patterns, and I'm curious about this one. 我仍在学习javascript模式,对此感到很好奇。

If I have an array of objects, should I make the array of objects not have keys (Example A), or use their keys (Example B)? 如果我有一个对象数组,是否应该使对象数组没有键(示例A),或者使用其键(示例B)?

An array of objects without any key: 没有任何键的对象数组:

var soylent_green_candidates = [{
  id: 12341,
  name: "Don",
  gender: "Male",
  weapon_of_choice: "Kangaroo Cannon"
},
{
  id: 24325,
  name: "Jimmy",
  gender: "Male",
  weapon_of_choice: "Sushi Blaster"
},
...
]

Or an array of objects using the unique ID's as keys: 或使用唯一ID作为键的对象数组:

var soylent_green_candidates = [ 
12341: {
  name: "Don",
  gender: "Male",
  weapon_of_choice: "Kangaroo Cannon"
},
24325: {
  name: "Jimmy",
  gender: "Male",
  weapon_of_choice: "Sushi Blaster"
},
...
]

Your second example is invalid, so that should put the question to sleep. 您的第二个示例是无效的,因此应该将问题搁浅。

In Javascript you have the option of arrays , which are sorted but essentially "key less". 在Javascript中,您可以选择数组 ,这些数组经过排序,但本质上是“少键”。 Each array entry can only be accessed by its numeric index, period. 每个数组条目只能通过其数字索引句点来访问。
The other option is objects , which have no guaranteed order but are keyed by arbitrary values. 另一个选项是object ,它们没有保证的顺序,但由任意值键入。

['foo', 'bar', 'baz']
{ foo : 'bar', baz : 42 }

You make the choice based on these two criteria, order and requirement for keys. 您基于这两个标准(密钥的顺序和要求)进行选择。

(Note: while you can use arbitrary numeric indices for arrays, you can't do so using the literal syntax [..] , and it's not usually a good idea. If you need explicit keys, you want objects.) (注意:虽然可以对数组使用任意数字索引,但不能使用文字语法[..]这样做,通常不是一个好主意。如果需要显式键,则需要对象。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JS-在这种情况下,我应该使用数组(包含对象)还是对象(包含对象) - JS - In this kind of case, should I use an array (containing objects) or an object (containing objects) 当对象数组在每个 object 中具有不同的键时,我想根据不同的键进行过滤 - When array of objects has different keys in each object I want to filter based on the different keys JS将带有对象值的数组分配给对象键 - JS assign array with objects values to object keys 通过对象属性识别对象数组 - Identify an array of objects by object property JS从对象数组中获取所有对象键的联合 - JS getting union of all object keys from an array of objects 在对 arrays 的 js object 进行排序时,它返回键数组而不是对象 - while sorting js object of arrays, it is returning keys array instead of objects 使用对象键将javascript对象数组划分为多个数组 - Use object keys to divide javascript array of objects into multiple arrays 错误:对象作为 React 子项无效(找到:object,键为 {})。 如果您打算渲染子集合,请改用数组。 JS - Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead. JS 使用数组作为 object 键 - Use array as object keys 带有键JSON的对象到对象的数组 - Array of objects to object with keys JSON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM