Arrays 反应本机:键值数组还是hasmap?
我想在我的react原生应用程序中创建一个数组/集合/hasmap,其中一个键链接到一个值。因为我来自PHP,我将给你一个简短的例子来说明我的意思。在PHP中,您只需创建一个具有键/值对的数组,如下所示:Arrays 反应本机:键值数组还是hasmap?,arrays,reactjs,react-native,hashmap,Arrays,Reactjs,React Native,Hashmap,我想在我的react原生应用程序中创建一个数组/集合/hasmap,其中一个键链接到一个值。因为我来自PHP,我将给你一个简短的例子来说明我的意思。在PHP中,您只需创建一个具有键/值对的数组,如下所示: $array = array( 41 => "bar", 65 => "foo", ); var votes = []; responseJson.map((product, key) => { var productID = product.id;
$array = array(
41 => "bar",
65 => "foo",
);
var votes = [];
responseJson.map((product, key) => {
var productID = product.id;
votes.push({
productID: product.votes
});
});
console.log("Votes:", votes);
312: "0"
521: "1"
741: "2"
633: "0"
653: "8"
873: "4"
这也是我想在我的本地地图中看到的。链接到值的键。现在我是这样做的:
$array = array(
41 => "bar",
65 => "foo",
);
var votes = [];
responseJson.map((product, key) => {
var productID = product.id;
votes.push({
productID: product.votes
});
});
console.log("Votes:", votes);
312: "0"
521: "1"
741: "2"
633: "0"
653: "8"
873: "4"
然而,我最后得到的是:
0: {productID: "0"}
1: {productID: "1"}
2: {productID: "2"}
3: {productID: "0"}
4: {productID: "8"}
5: {productID: "4"}
首先,productID变量被打印为name,而不是value。。第一个错误。。。第二,我想要这样的东西:
$array = array(
41 => "bar",
65 => "foo",
);
var votes = [];
responseJson.map((product, key) => {
var productID = product.id;
votes.push({
productID: product.votes
});
});
console.log("Votes:", votes);
312: "0"
521: "1"
741: "2"
633: "0"
653: "8"
873: "4"
你们知道我怎么做吗
亲切的问候和感谢 您可以使用括号表示法 例如:
var votes = [];
responseJson.map((product, key) => {
var productID = product.id;
votes.push({
[productID]: product.votes
});
});
console.log("Votes:", votes);
在javascript中,您可以使用object作为存储键值对的方法 如果要使用变量定义键,应该执行以下操作
votes.push({
[productID]: product.votes
});
你可以通过做类似的事情来实现你想要的-
var votes = {};
responseJson.forEach((product, key) => {
var productID = product.id;
votes[productID] = product.votes
});
console.log("Votes:", votes);
希望能有所帮助。是的,但投票数组中还有数组。我想让它直接链接,而不需要数组中的数组!你愿意给我回复吗?所以我会给你一个更好的解决方案。谢谢。请看下面的答案。这就是我要找的。但是谢谢你!谢谢,这就是我要找的!