0

so I'm trying to replicate an HTTP payload which has two same keys with different values.

const x = {};
x['house'] = 'table';
x['house'] = 'food';

The above doesnt work. Is there another alternative?

  • "HTTP payload" do you mean JSON? – evolutionxbox Jan 31 '20 at 17:13
  • You need an array of values `x['house'] = ['table', 'food']` – Zohaib Ijaz Jan 31 '20 at 17:13
  • Does this answer your question? [Does JSON syntax allow duplicate keys in an object?](https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object) – evolutionxbox Jan 31 '20 at 17:14
  • 2
    Use a [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) object or a [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object – Titus Jan 31 '20 at 17:15

1 Answers1

5

The usual way to do that is to use an array:

const x = {};
x.house = ["table", "food"];

Or

const x = {
    house: ["table", "food"]
};

You could also use a Set:

const x = {
    house: new Set()
};
x.house.add("table");
x.house.add("food");

or

const x = {
    house: new Set(["table", "food"])
};

I've used dot notation above, but you can use brackets notation as you did in your question if you prefer:

const x = {};
x["house"] = ["table", "food"];
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • If the HTTP payload has duplicate keys, wouldn't it be better to use a string, and then parse it? – evolutionxbox Jan 31 '20 at 17:26
  • This doesn't quite work for me because I need the two values to be in a separate key with the same name – Miguel Betancourt Jan 31 '20 at 17:26
  • @MiguelBetancourt - What's the use case? (I can't think of one.) It's impossible to have two properties in the same JavaScript object with the same name, and a JavaScript property can have only **one** value, so it's a matter of using that one value to refer to multiple things, whether that's an array, another plain object, an object like a Set, a string you parse as evolutionxbox mentioned, or a `FormData` object as Titus mentioned, etc. – T.J. Crowder Jan 31 '20 at 17:36
  • I'm trying to simulate a POST request with a payload which has two keys with the same name but a different value – Miguel Betancourt Jan 31 '20 at 17:45
  • @MiguelBetancourt - That just doesn't exist in JavaScript (other than as described above). (`FormData` gets you close.) For example, JavaScript-based server-side mechanisms for receiving HTTP requests give you arrays for repeated parameters; [example](https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions). – T.J. Crowder Jan 31 '20 at 17:52