JavaScript 中是否有任何键/值对结构?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6771763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any key/value pair structure in JavaScript?
提问by sushil bharwani
I want to store information like:
我想存储如下信息:
Pseudo-Code
伪代码
array(manager) = {"Prateek","Rudresh","Prashant"};
array(employee) = {"namit","amit","sushil"};
array(hr) = {"priya","seema","nakul"};
What kind of data structure can I use?
我可以使用什么样的数据结构?
回答by Pascal MARTIN
You can use arraysto store list of data ; and objectsfor key-value
In you case, you'd probably use both :
在您的情况下,您可能会同时使用两者:
var data = {
'manager': ["Prateek","Rudresh","Prashant"],
'employee': ["namit","amit","sushil"],
'hr': ["priya","seema","nakul"]
};
Here, data
is an object ; which contains three arrays.
这里,data
是一个对象;其中包含三个数组。
回答by Paul
An object:
一个东西:
var myobj = {
"manager": ["Prateek","Rudresh","Prashant"],
"employee": ["namit","amit","sushil"],
"hr": ["priya","seema","nakul"]
}
alert(myobj['employee'][1]); // Outputs "amit"
回答by Shurdoof
A normal object will do:
一个普通的对象会做:
var a = {
key1: "value1",
key2: ["value2.1","value2.2"]
/*etc*/
}
Access with:
访问方式:
a.key1
a["key1"]
回答by dangerdave
you could store them in an array of objects:
你可以将它们存储在一个对象数组中:
var Staff = [
{ name: 'Prateek', role: manager },
{ name: 'Rudresh', role: manager },
{ name: 'Prashant', role: manager },
{ name: 'Namit', role: employee },
{ name: 'Amit', role: employee },
{ name: 'Sushil', role: employee },
{ name: 'Priya', role: hr },
{ name: 'Seema', role: hr },
{ name: 'Nakul', role: hr },
];
adding an ID attribute might be useful too depending on your application. i.e
根据您的应用程序,添加 ID 属性也可能很有用。IE
{ id: 223, name: 'Prateek', role: manager },
回答by Vlad Bezden
With ES2015/ES6 you have Maptype.
在 ES2015/ES6 中,你有Map类型。
Using Map your code will look like
使用 Map 你的代码看起来像
const map = new Map([
['manager', ['Prateek', 'Rudresh', 'Prashant']],
['employee', ['namit', 'amit', 'sushil']],
['hr', ['priya', 'seema', 'nakul']]
])
console.log(...map.entries())
To get Individual value you can use Map.get('key')method
要获取个人值,您可以使用Map.get('key')方法
回答by Bakudan
Or use JSON like this. A little change of your pseudo code, but it will be serchable and extendable.
或者像这样使用 JSON。对您的伪代码稍作改动,但它将是可搜索和可扩展的。
var Person = [
{
"name": "Prateek",
"position": "manager"},
{
"name": "James",
"position": "employee"}
];
回答by Ibu
Yes there is:
就在这里:
var theArray = {};
theArray["manager"] = ["Prateek","Rudresh","Prashant"];
theArray["employee"] = ["namit","amit","sushil"];
theArray["hr"] = ["priya","seema","nakul"];
回答by Jatin Dhoot
Even you can use stuff as below :-
即使您可以使用以下内容:-
var obj = new Object();
obj.name = 'Jatin';
obj.place = 'Delhi';