如何在 JavaScript 中创建字典并动态添加键值对

发布于 2024-12-01 05:36:30 字数 460 浏览 2 评论 0原文

来自帖子:

发送一个 JSON 数组作为字典接收,

我正在尝试做与那篇文章相同的事情。唯一的问题是我不知道预先的键和值是什么。所以我需要能够动态添加键和值对,但我不知道该怎么做。

如何创建该对象并动态添加键值对?

我试过了:

var vars = [{key:"key", value:"value"}];
vars[0].key = "newkey";
vars[0].value = "newvalue";

但这不起作用。

From post:

Sending a JSON array to be received as a Dictionary<string,string>,

I'm trying to do this same thing as that post. The only issue is that I don't know what the keys and the values are upfront. So I need to be able to dynamically add the key and value pairs and I don't know how to do that.

How can I create that object and add key value pairs dynamically?

I've tried:

var vars = [{key:"key", value:"value"}];
vars[0].key = "newkey";
vars[0].value = "newvalue";

But that doesn't work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

梦纸 2024-12-08 05:36:30

使用:

var dict = []; // Create an empty array

dict.push({
    key:   "keyName",
    value: "the value"
});
// Repeat this last part as needed to add more key/value pairs

基本上,您正在创建一个具有两个属性(称为keyvalue)的对象文字并插入它(使用push())进入数组。


这不会创建“正常”JavaScript 对象文字(又名地图、又名散列、又名字典)。
然而,它正在创建 OP 要求的结构(在链接到的另一个问题中对此进行了说明),它是一个对象文字数组,每个数组都有 keyvalue 属性。不要问我为什么需要这种结构,但这是我们所要求的。

但是,但是,如果你想要一个普通的 JavaScript 对象 - 而不是 OP 要求的结构 - 请参阅 tcll 的答案,尽管如果您只有作为有效 JavaScript 名称的简单键,那么括号表示法有点麻烦。您可以这样做:

// Object literal with properties
var dict = {
  key1: "value1",
  key2: "value2"
  // etc.
};

或者在创建对象后使用常规点符号来设置属性:

// Empty object literal with properties added afterward
var dict = {};
dict.key1 = "value1";
dict.key2 = "value2";
// etc.

如果您的键中包含空格、特殊字符或其他内容,您确实需要括号符号像那样。例如:

var dict = {};

// This obviously won't work
dict.some invalid key (for multiple reasons) = "value1";

// But this will
dict["some invalid key (for multiple reasons)"] = "value1";

如果您的键是动态的,您还需要括号表示法:

dict[firstName + " " + lastName] = "some value";

请注意,键(属性名称)始终是字符串,并且非字符串值在用作键时将被强制为字符串。例如,Date 对象被转换为其字符串表示形式:

dict[new Date] = "today's value";

console.log(dict);
// => {
//      "Sat Nov 04 2016 16:15:31 GMT-0700 (PDT)": "today's value"
//    }

但请注意,这不一定“正常工作”,因为许多对象将具有类似 “[object Object]” 的字符串表示形式 这并不构成非唯一的密钥。因此,请注意以下内容:

var objA = { a: 23 },
    objB = { b: 42 };

dict[objA] = "value for objA";
dict[objB] = "value for objB";

console.log(dict);
// => { "[object Object]": "value for objB" }

尽管 objAobjB 是完全不同且独特的元素,但它们都具有相同的基本字符串表示形式:"[object Object]"

Date 之所以没有这样的行为,是因为 Date 原型有一个自定义的 toString 方法,该方法会覆盖默认的字符串表示形式。您也可以这样做:(

// A simple constructor with a toString prototypal method
function Foo() {
  this.myRandomNumber = Math.random() * 1000 | 0;
}

Foo.prototype.toString = function () {
  return "Foo instance #" + this.myRandomNumber;
};

dict[new Foo] = "some value";

console.log(dict);
// => {
//      "Foo instance #712": "some value"
//    }

请注意,由于上面使用了随机数字,因此仍然很容易发生名称冲突。这只是为了说明toString的实现。)

因此,当尝试使用对象作为键时,JavaScript 将使用对象自己的 toString 实现(如果有),或者使用默认的字符串表示形式。

Use:

var dict = []; // Create an empty array

dict.push({
    key:   "keyName",
    value: "the value"
});
// Repeat this last part as needed to add more key/value pairs

Basically, you're creating an object literal with two properties (called key and value) and inserting it (using push()) into the array.


This does not create a "normal" JavaScript object literal (aka map, aka hash, aka dictionary).
It is however creating the structure that OP asked for (and which is illustrated in the other question linked to), which is an array of object literals, each with key and value properties. Don't ask me why that structure was required, but it's the one that was asked for.

But, but, if what you want in a plain JavaScript object - and not the structure OP asked for - see tcll's answer, though the bracket notation is a bit cumbersome if you just have simple keys that are valid JavaScript names. You can just do this:

// Object literal with properties
var dict = {
  key1: "value1",
  key2: "value2"
  // etc.
};

Or use regular dot-notation to set properties after creating an object:

// Empty object literal with properties added afterward
var dict = {};
dict.key1 = "value1";
dict.key2 = "value2";
// etc.

You do want the bracket notation if you've got keys that have spaces in them, special characters, or things like that. E.g:

var dict = {};

// This obviously won't work
dict.some invalid key (for multiple reasons) = "value1";

// But this will
dict["some invalid key (for multiple reasons)"] = "value1";

You also want bracket notation if your keys are dynamic:

dict[firstName + " " + lastName] = "some value";

Note that keys (property names) are always strings, and non-string values will be coerced to a string when used as a key. E.g., a Date object gets converted to its string representation:

dict[new Date] = "today's value";

console.log(dict);
// => {
//      "Sat Nov 04 2016 16:15:31 GMT-0700 (PDT)": "today's value"
//    }

Note however that this doesn't necessarily "just work", as many objects will have a string representation like "[object Object]" which doesn't make for a non-unique key. So be wary of something like:

var objA = { a: 23 },
    objB = { b: 42 };

dict[objA] = "value for objA";
dict[objB] = "value for objB";

console.log(dict);
// => { "[object Object]": "value for objB" }

Despite objA and objB being completely different and unique elements, they both have the same basic string representation: "[object Object]".

The reason Date doesn't behave like this is that the Date prototype has a custom toString method which overrides the default string representation. And you can do the same:

// A simple constructor with a toString prototypal method
function Foo() {
  this.myRandomNumber = Math.random() * 1000 | 0;
}

Foo.prototype.toString = function () {
  return "Foo instance #" + this.myRandomNumber;
};

dict[new Foo] = "some value";

console.log(dict);
// => {
//      "Foo instance #712": "some value"
//    }

(Note that since the above uses a random number, name collisions can still occur very easily. It's just to illustrate an implementation of toString.)

So when trying to use objects as keys, JavaScript will use the object's own toString implementation, if any, or use the default string representation.

浅浅淡淡 2024-12-08 05:36:30

使用:

var dict = {};

dict['key'] = "testing";

console.log(dict);

它的工作方式就像 Python :)

控制台输出:

Object {key: "testing"}

Use:

var dict = {};

dict['key'] = "testing";

console.log(dict);

It works just like Python :)

Console output:

Object {key: "testing"}
终陌 2024-12-08 05:36:30

就像这样简单:

var blah = {}; // Make a new dictionary (empty)

var blah = {key: value, key2: value2}; // Make a new dictionary with two pairs 

然后

blah.key3 = value3; // Add a new key/value pair
blah.key2; // Returns value2
blah['key2']; // Also returns value2

It’s as simple as:

var blah = {}; // Make a new dictionary (empty)

or

var blah = {key: value, key2: value2}; // Make a new dictionary with two pairs 

Then

blah.key3 = value3; // Add a new key/value pair
blah.key2; // Returns value2
blah['key2']; // Also returns value2
强者自强 2024-12-08 05:36:30

既然您已经声明您想要一个字典对象(并且不是数组,就像我假设有些人理解的那样),我认为这就是您所追求的:

var input = [{key:"key1", value:"value1"},{key:"key2", value:"value2"}];

var result = {};

for(var i = 0; i < input.length; i++)
{
    result[input[i].key] = input[i].value;
}

console.log(result); // Just for testing

Since you've stated that you want a dictionary object (and not an array like I assume some understood) I think this is what you are after:

var input = [{key:"key1", value:"value1"},{key:"key2", value:"value2"}];

var result = {};

for(var i = 0; i < input.length; i++)
{
    result[input[i].key] = input[i].value;
}

console.log(result); // Just for testing
绝對不後悔。 2024-12-08 05:36:30

JavaScript 的 Object 本身就像一本字典。无需重新发明轮子。

var dict = {};

// Adding key-value -pairs
dict['key'] = 'value'; // Through indexer
dict.anotherKey = 'anotherValue'; // Through assignment

// Looping through
for (var item in dict) {
  console.log('key:' + item + ' value:' + dict[item]);
  // Output
  // key:key value:value
  // key:anotherKey value:anotherValue
}

// Non existent key
console.log(dict.notExist); // undefined

// Contains key?
if (dict.hasOwnProperty('key')) {
  // Remove item
  delete dict.key;
}

// Looping through
for (var item in dict) {
  console.log('key:' + item + ' value:' + dict[item]);
  // Output
  // key:anotherKey value:anotherValue
}

小提琴

JavaScript's Object is in itself like a dictionary. No need to reinvent the wheel.

var dict = {};

// Adding key-value -pairs
dict['key'] = 'value'; // Through indexer
dict.anotherKey = 'anotherValue'; // Through assignment

// Looping through
for (var item in dict) {
  console.log('key:' + item + ' value:' + dict[item]);
  // Output
  // key:key value:value
  // key:anotherKey value:anotherValue
}

// Non existent key
console.log(dict.notExist); // undefined

// Contains key?
if (dict.hasOwnProperty('key')) {
  // Remove item
  delete dict.key;
}

// Looping through
for (var item in dict) {
  console.log('key:' + item + ' value:' + dict[item]);
  // Output
  // key:anotherKey value:anotherValue
}

Fiddle

难忘№最初的完美 2024-12-08 05:36:30

您可以将地图与 Map 结合使用,像这样:

var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');

You can use maps with Map, like this:

var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');
硬不硬你别怂 2024-12-08 05:36:30

使用 ES6,您可以执行以下操作:

let cake = '

With ES6, you can do this:

let cake = '????';

let pan = {
  [cake]: '????',
};

// Output -> { '????': '????' }

Old Way (vanilla JavaScript)

let cake = '????';
let pan = {};
pan[cake] = '????';

// Output -> { '????': '????' }
屋顶上的小猫咪 2024-12-08 05:36:30

我碰巧遇到这个问题寻找类似的东西。它为我提供了足够的信息来运行测试以获得我想要的答案。因此,如果其他人想知道如何在 JavaScript 对象中动态添加或查找 {key: 'value'} 对,此测试应该告诉您可能需要知道的所有信息。

var dictionary = {initialkey: 'initialValue'};
var key = 'something';
var key2 =  'somethingElse';
var value = 'value1';
var value2 = 'value2';
var keyInitial = 'initialkey';

console.log(dictionary[keyInitial]);

dictionary[key] =value;
dictionary[key2] = value2;
console.log(dictionary);

输出

initialValue
{ initialkey: 'initialValue',
  something: 'value1',
  somethingElse: 'value2' }

I happened to walk across this question looking for something similar. It gave me enough info to run a test to get the answer I wanted. So if anyone else wants to know how to dynamically add to or lookup a {key: 'value'} pair in a JavaScript object, this test should tell you all you might need to know.

var dictionary = {initialkey: 'initialValue'};
var key = 'something';
var key2 =  'somethingElse';
var value = 'value1';
var value2 = 'value2';
var keyInitial = 'initialkey';

console.log(dictionary[keyInitial]);

dictionary[key] =value;
dictionary[key2] = value2;
console.log(dictionary);

output

initialValue
{ initialkey: 'initialValue',
  something: 'value1',
  somethingElse: 'value2' }
写给空气的情书 2024-12-08 05:36:30
var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1
var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1
泪痕残 2024-12-08 05:36:30

在现代 JavaScript (ES6/ES2015) 中,应该使用字典的Map数据结构。 ES6 中的 Map 数据结构允许您使用任意值作为键。

const map = new Map();
map.set("true", 1);
map.set("false", 0);

在您仍在使用 ES5 时,正确的创建方法字典是通过以下方式创建没有原型的对象。

var map = Object.create(null);
map["true"] = 1;
map["false"] = 0;

创建没有原型对象的字典有很多优点。以下关于该主题的博客文章值得一读。

字典模式

对象作为地图

In modern JavaScript (ES6/ES2015), one should use the Map data structure for a dictionary. The Map data structure in ES6 lets you use arbitrary values as keys.

const map = new Map();
map.set("true", 1);
map.set("false", 0);

In you are still using ES5, the correct way to create dictionary is to create object without a prototype in the following way.

var map = Object.create(null);
map["true"] = 1;
map["false"] = 0;

There are many advantages of creating a dictionary without a prototype object. The below blog posts are worth reading on this topic.

dict-pattern

objects-as-maps

请叫√我孤独 2024-12-08 05:36:30

首先全局初始化数组:

var dict = []

将对象添加到字典中

dict.push(
     { key: "One",value: false},
     { key: "Two",value: false},
     { key: "Three",value: false});

输出:

   [0: {key: "One", value: false}
    1: {key: "Two", value: false}
    2: {key: "Three", value: false}]

从字典中更新对象

Object.keys(dict).map((index) => {
  if (index == 1){
    dict[index].value = true
  }
});

输出:

   [0: {key: "One", value: false},
    1: {key: "Two", value: true},
    2: {key: "Three", value: false}]

从字典中删除对象

Object.keys(dict).map((index) => {
      if (index == 2){
        dict.splice(index)
      }
    });

输出:

    [0: {key: "One", value: false},
     1: {key: "Two", value: true}]

First initialise the array globally:

var dict = []

Add the object into the dictionary

dict.push(
     { key: "One",value: false},
     { key: "Two",value: false},
     { key: "Three",value: false});

Output:

   [0: {key: "One", value: false}
    1: {key: "Two", value: false}
    2: {key: "Three", value: false}]

Update the object from the dictionary

Object.keys(dict).map((index) => {
  if (index == 1){
    dict[index].value = true
  }
});

Output:

   [0: {key: "One", value: false},
    1: {key: "Two", value: true},
    2: {key: "Three", value: false}]

Delete an object from the dictionary

Object.keys(dict).map((index) => {
      if (index == 2){
        dict.splice(index)
      }
    });

Output:

    [0: {key: "One", value: false},
     1: {key: "Two", value: true}]
ζ澈沫 2024-12-08 05:36:30

您可以创建一个字典类,以便可以轻松地与字典列表进行交互:

class Dictionary {
  constructor() {
    this.items = {};
  }
  has(key) {
    return key in this.items;
  }
  set(key,value) {
    this.items[key] = value;
  }
  delete(key) {
    if( this.has(key) ){
      delete this.items[key]
      return true;
    }
    return false;
  }
}

var d = new Dictionary();
d.set(1, "value1")
d.set(2, "value2")
d.set(3, "value3")
console.log(d.has(2));
d.delete(2);
console.log(d.has(2));

You could create a class Dictionary so you can interact with the Dictionary list easily:

class Dictionary {
  constructor() {
    this.items = {};
  }
  has(key) {
    return key in this.items;
  }
  set(key,value) {
    this.items[key] = value;
  }
  delete(key) {
    if( this.has(key) ){
      delete this.items[key]
      return true;
    }
    return false;
  }
}

var d = new Dictionary();
d.set(1, "value1")
d.set(2, "value2")
d.set(3, "value3")
console.log(d.has(2));
d.delete(2);
console.log(d.has(2));

烟燃烟灭 2024-12-08 05:36:30

var dict = {} 的改进是使用 var dict = Object.create(null)

这将创建一个空对象,Object.prototype作为其原型。

var dict1 = {};
if (dict1["toString"]){
    console.log("Hey, I didn't put that there!")
}

var dict2 = Object.create(null);
if (dict2["toString"]){
    console.log("This line won't run :)")
}

An improvement on var dict = {} is to use var dict = Object.create(null).

This will create an empty object that does not have Object.prototype as its prototype.

var dict1 = {};
if (dict1["toString"]){
    console.log("Hey, I didn't put that there!")
}

var dict2 = Object.create(null);
if (dict2["toString"]){
    console.log("This line won't run :)")
}
马蹄踏│碎落叶 2024-12-08 05:36:30

使用单行代码创建键值对:

let result = { ["foo"]: "some value" };

以及一些迭代器函数,例如 reduce 来动态地将数组转换为字典

var options = [
  { key: "foo", value: 1 },
  { key: "bar", value: {id: 2, name: "two"} },
  { key: "baz", value: {["active"]: true} },
];

var result = options.reduce((accumulator, current) => {
  accumulator[current.key] = current.value;
  return accumulator;
}, {});

console.log(result);

Use a one-liner for creating a key value pair:

let result = { ["foo"]: "some value" };

And some iterator function like reduce to dynamically convert an array to a dictionary

var options = [
  { key: "foo", value: 1 },
  { key: "bar", value: {id: 2, name: "two"} },
  { key: "baz", value: {["active"]: true} },
];

var result = options.reduce((accumulator, current) => {
  accumulator[current.key] = current.value;
  return accumulator;
}, {});

console.log(result);

初心未许 2024-12-08 05:36:30

我遇到了这个问题......但是在 for 循环中。顶级解决方案不起作用(当使用变量(而不是字符串)作为推送函数的参数时),其他解决方案没有考虑基于变量的键值。我很惊讶这种方法(这在 PHP 中很常见)有效......

// Example dict/JSON
var iterateDict = {'record_identifier': {'content':'Some content', 'title':'Title of my Record'},
  'record_identifier_2': {'content':'Some  different content', 'title':'Title of my another Record'} };

var array = [];

// Key to reduce the 'record' to
var reduceKey = 'title';

for(key in iterateDict)
 // Ultra-safe variable checking...
 if(iterateDict[key] !== undefined && iterateDict[key][reduceKey] !== undefined)
  // Build element to new array key
   array[key] = iterateDict[key][reduceKey];

I ran into this problem... but within a for loop. The top solution did not work (when using variables (and not strings) for the parameters of the push function), and the others did not account for key values based on variables. I was surprised this approach (which is common in PHP) worked...

// Example dict/JSON
var iterateDict = {'record_identifier': {'content':'Some content', 'title':'Title of my Record'},
  'record_identifier_2': {'content':'Some  different content', 'title':'Title of my another Record'} };

var array = [];

// Key to reduce the 'record' to
var reduceKey = 'title';

for(key in iterateDict)
 // Ultra-safe variable checking...
 if(iterateDict[key] !== undefined && iterateDict[key][reduceKey] !== undefined)
  // Build element to new array key
   array[key] = iterateDict[key][reduceKey];
难忘№最初的完美 2024-12-08 05:36:30

如果有人需要动态创建字典对象,您可以使用以下代码片段

let vars = [{key:"key", value:"value"}, {key:"key2", value:"value2"}];
let dict = {}
vars.map(varItem => {
             dict[varItem.key] = varItem.value
         })

console.log(dict)

In case if someone needs to create a dictionary object dynamically you can use the following code snippet

let vars = [{key:"key", value:"value"}, {key:"key2", value:"value2"}];
let dict = {}
vars.map(varItem => {
             dict[varItem.key] = varItem.value
         })

console.log(dict)

半枫 2024-12-08 05:36:30

您可以像这样初始化字典

var vars = {
    "key1": "Search",
    "key2": "View"
};

并像这样访问它

console.log(vars["key1"]);

You can initialize the dictionary like

var vars = {
    "key1": "Search",
    "key2": "View"
};

And access it like

console.log(vars["key1"]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文