JavaScript中是否有任何键/值对结构?

时间:2011-07-21 05:48:04

标签: javascript

我想存储以下信息:

伪代码

array(manager) = {"Prateek","Rudresh","Prashant"};
array(employee) = {"namit","amit","sushil"};
array(hr) = {"priya","seema","nakul"};

我可以使用哪种数据结构?

8 个答案:

答案 0 :(得分:35)

您可以使用arrays来存储数据列表;和objects的键值


在你的情况下,你可能会同时使用两者:

var data = {
    'manager': ["Prateek","Rudresh","Prashant"], 
    'employee': ["namit","amit","sushil"], 
    'hr': ["priya","seema","nakul"]
};

这里,data是一个对象;其中包含三个数组。

答案 1 :(得分:13)

一个对象:

var myobj = {
  "manager": ["Prateek","Rudresh","Prashant"],
  "employee": ["namit","amit","sushil"],
  "hr": ["priya","seema","nakul"]
}

alert(myobj['employee'][1]); // Outputs "amit"

答案 2 :(得分:10)

普通对象会:

var a = {
    key1: "value1",
    key2: ["value2.1","value2.2"]
    /*etc*/
}

访问:

a.key1
a["key1"]

答案 3 :(得分:6)

你可以将它们存储在一个对象数组中:

    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 },
    ];

添加ID属性也可能有用,具体取决于您的应用程序。即

    { id: 223, name: 'Prateek', role: manager },

答案 4 :(得分:4)

使用ES2015 / ES6,您有Map类型。

使用Map你的代码看起来像

const map = new Map([
  ['manager', ['Prateek', 'Rudresh', 'Prashant']],
  ['employee', ['namit', 'amit', 'sushil']],
  ['hr', ['priya', 'seema', 'nakul']]
])

console.log(...map.entries())

要获得Individual值,您可以使用Map.get('key')方法

答案 5 :(得分:2)

是的,有:

var theArray = {};
theArray["manager"] = ["Prateek","Rudresh","Prashant"];
theArray["employee"] = ["namit","amit","sushil"];
theArray["hr"] = ["priya","seema","nakul"];

答案 6 :(得分:2)

或者像这样使用JSON。您的伪代码稍有变化,但它可以进行配置和扩展。

var Person = [
{
    "name": "Prateek",
    "position": "manager"},
{
    "name": "James",
    "position": "employee"}

];

答案 7 :(得分:-1)

即使您可以使用以下内容: -

var obj = new Object();

obj.name = 'Jatin';
obj.place = 'Delhi';