简体   繁体   中英

Multiple keys with same value in javascript object

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM