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?

4
  • "HTTP payload" do you mean JSON? Commented Jan 31, 2020 at 17:13
  • You need an array of values x['house'] = ['table', 'food'] Commented Jan 31, 2020 at 17:13
  • Does this answer your question? Does JSON syntax allow duplicate keys in an object? Commented Jan 31, 2020 at 17:14
  • 2
    Use a FormData object or a URLSearchParams object Commented Jan 31, 2020 at 17:15

1 Answer 1

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"];
Sign up to request clarification or add additional context in comments.

5 Comments

If the HTTP payload has duplicate keys, wouldn't it be better to use a string, and then parse it?
This doesn't quite work for me because I need the two values to be in a separate key with the same name
@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.
I'm trying to simulate a POST request with a payload which has two keys with the same name but a different value
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.