javascript对象中具有相同值的多个键

时间:2020-01-31 17:12:33

标签: javascript

所以我试图复制一个HTTP有效负载,该负载具有两个相同的键,但值不同。

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

以上无效。还有其他选择吗?

1 个答案:

答案 0 :(得分:5)

通常的方法是使用array

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

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

您还可以使用Set

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

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

我在上面使用了点符号,但是如果您愿意,也可以像在问题中一样使用方括号符号:

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