Jak tworzyć słownik i dynamicznie dodawać pary klucz–wartość?

From post:

Wysyłanie tablicy JSON do odebrania jako słownik

Próbuję zrobić to samo co ten post. Jedynym problemem jest to, że nie wiem, jakie klucze i wartości są z góry. Więc muszę być w stanie dynamicznie dodawać pary klucz i wartość i nie wiem, jak to zrobić.

Czy ktoś wie jak utworzyć ten obiekt i dynamicznie dodać pary wartości klucza?

Próbowałem:

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

Ale to nie praca.

Author: Xufox, 2011-08-25

13 answers

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

Zasadniczo tworzysz obiekt z 2 właściwościami (nazwanymi key i value) i wstawiasz go (używając push()) do tablicy.


Edit: a więc prawie 5 lat później ta odpowiedź jest coraz gorsza, ponieważ nie tworzy" normalnego " obiektu JS (aka map, aka hash, aka słownik).
To jest jednak tworzy strukturę, o którą prosił OP (i która jest zilustrowana w innym pytaniu, do którego jest link), która jest tablicą z literałów obiektów, każdy z właściwościami key i value. Nie pytaj mnie, dlaczego ta struktura była wymagana, ale to ta, o którą poproszono.

Ale, Ale, jeśli to, co chcesz w zwykłym obiekcie JS-a Nie struktura, o którą prosił OP-zobacz odpowiedź tcll , chociaż notacja nawiasów jest nieco uciążliwa, jeśli masz tylko proste klucze, które są poprawnymi nazwami JS. Możesz po prostu to zrobić:

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

Lub użyj zwykłej notacji kropkowej, aby ustawić właściwości po utworzeniu obiekt:

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

You do chcesz notacji nawiasów, jeśli masz klucze, które mają spacje w nich, znaki specjalne, lub rzeczy w tym stylu. Np.:

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";

Chcesz również notację nawiasów, jeśli Twoje klucze są dynamiczne:

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

Zauważ, że klucze (nazwy właściwości) są zawsze łańcuchami znaków, a wartości nie-łańcuchowe będą wymuszane do łańcucha znaków, gdy zostaną użyte jako klucz. Np. obiekt Date zostanie przekonwertowany na jego reprezentację łańcuchową:

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

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

Zauważ jednak, że to nie musi "po prostu działać", ponieważ wiele obiektów będzie miało reprezentację łańcuchową, taką jak "[object Object]", która nie tworzy unikalnego klucza. Więc uważaj na coś takiego:

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" }

Pomimo, że objA i objB są zupełnie różnymi i unikalnymi elementami, oba mają tę samą podstawową reprezentację ciągu: "[object Object]".

Powodem, dla którego Date nie zachowuje się tak, jest to, że prototyp Date ma własną metodę toString, która nadpisuje domyślną reprezentację ciągu znaków. I możesz to zrobić to samo:

// 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"
//    }

(zauważ, że ponieważ powyższe używa losowej liczby, kolizje nazw mogą nadal występować bardzo łatwo. To tylko ilustracja implementacji toString.)

Więc podczas próby użycia obiektów jako kluczy, JS użyje własnej implementacji toString obiektu, jeśli taka istnieje, lub użyje domyślnej reprezentacji ciągu znaków.

 373
Author: Flambino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:26
var dict = {};

dict['key'] = "testing";

console.log(dict);

Działa jak python:)

Wyjście konsoli:

Object {key: "testing"} 
 313
Author: Tcll,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-22 08:04:10

Its as simple as:

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

Lub

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
 50
Author: Simon Sarris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-25 19:54:04

Skoro stwierdziłeś, że chcesz obiekt słownika (i a nie tablicę jak zakładam niektórzy rozumieją) myślę, że to jest to, czego szukasz:

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
 31
Author: ZenMaster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-25 20:04:57

JavaScript ' s Object jest samym w sobie jak słownik. Nie musisz odkrywać koła na nowo.

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

 16
Author: Jani Hyytiäinen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-19 15:44:44

Zdarzyło mi się przejść przez to pytanie szukając czegoś podobnego. To dało mi wystarczająco dużo informacji, aby przeprowadzić test, aby uzyskać odpowiedź, którą chciałem. Jeśli więc ktoś jeszcze chce wiedzieć, jak dynamicznie dodać do lub wyszukać parę {key: 'value'} w obiekcie JavaScript, ten test powinien powiedzieć Ci wszystko, co powinieneś wiedzieć.

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);

Wyjście

initialValue
{ initialkey: 'initialValue',
  something: 'value1',
  somethingElse: 'value2' }
 8
Author: user2301449,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-02 02:11:18
var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1
 6
Author: SharpCoder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-02 13:35:12

Możesz używać map z Map, Tak:

var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');
 4
Author: Preetham Kumar P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-07 02:35:11

Możesz utworzyć Słownik klas, dzięki czemu możesz łatwo wchodzić w interakcje z listą słownika:

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));
 2
Author: agonza1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-04 14:23:08

Natknąłem się na ten problem.. ale w pętli for. Najlepsze rozwiązanie nie działało (przy użyciu zmiennych (a nie łańcuchów) dla parametrów funkcji push), a pozostałe nie uwzględniały wartości kluczowych opartych na zmiennych. Byłem zaskoczony, że takie podejście (które jest powszechne w php) zadziałało..

  // 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];
 1
Author: redcap3000,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-24 22:13:57

A może jedna linijka do tworzenia pary wartości klucza?

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

I niektóre funkcje iteratora jak reduce do dynamicznej konwersji tablicy do słownika

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);
 1
Author: Dan Dohotaru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-16 23:26:46

Pomogłoby Tony wiedzieć, jaki jest twój końcowy pożądany rezultat, ale myślę, że tego chcesz:

var vars = [{key:"key", value:"value"}];

vars.push({key: "newkey", value: "newvalue"})
 0
Author: g.d.d.c,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-25 19:46:43

Ulepszeniem na var dict = {} jest użycie var dict = Object.create(null).

Spowoduje to utworzenie pustego obiektu, który nie mA Object.prototype jako prototyp.

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 :)")
}
 0
Author: WoodenKitty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-20 07:53:57