admin管理员组文章数量:1126104
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.
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.
Share Improve this question edited Apr 16, 2023 at 17:05 Peter Mortensen 31.6k22 gold badges109 silver badges133 bronze badges asked Aug 25, 2011 at 19:39 KenEuckerKenEucker 5,0895 gold badges25 silver badges28 bronze badges 3 |17 Answers
Reset to default 714Use:
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.
Use:
var dict = {};
dict['key'] = "testing";
console.log(dict);
It works just like Python :)
Console output:
Object {key: "testing"}
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
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
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
You can use maps with Map
, like this:
var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');
With ES6, you can do this:
let cake = '
本文标签:
How to create a dictionary and add key value pairs dynamically in JavaScriptStack Overflow
版权声明:本文标题:How to create a dictionary and add key value pairs dynamically in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人,
转载请联系作者并注明出处:http://www.betaflare.com/web/1736682227a1947477.html,
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
list = [["key1","value1"],["key2","value2"]]
. Some other languages have a "pair", or "tuple" type. tldr for actual dict adding:dict['key'] = "value"
– Jordan Stewart Commented Mar 19, 2020 at 11:36