React Native: Key Value array or hasmap?
Solution 1
In javascript you can use object as a method to store key-value pairs.
If you want to define keys using variables you should do something like this
votes.push({
[productID]: product.votes
});
You can achieve what you want by doing something similar to this -
var votes = {};
responseJson.forEach((product, key) => {
var productID = product.id;
votes[productID] = product.votes
});
console.log("Votes:", votes);
Hope it help.
Solution 2
You can use the bracket notation for it.
Example:
var votes = [];
responseJson.map((product, key) => {
var productID = product.id;
votes.push({
[productID]: product.votes
});
});
console.log("Votes:", votes);
Jan
Updated on June 13, 2022Comments
-
Jan almost 2 years
I would like to create an array/collection/hasmap in my react native app where a key is linked to a value. Cause I am coming from PHP I will give you a short example of what I mean. In PHP you simply create an array with key/value pair like this:
$array = array( 41 => "bar", 65 => "foo", );
This is what I want to have too in my react native map. A key linking to a value. Right now I am doing it like this:
var votes = []; responseJson.map((product, key) => { var productID = product.id; votes.push({ productID: product.votes }); }); console.log("Votes:", votes);
However, what I get at the end is this:
0: {productID: "0"} 1: {productID: "1"} 2: {productID: "2"} 3: {productID: "0"} 4: {productID: "8"} 5: {productID: "4"}
First of all, the productID variable gets printed as name and not as the value.. First error... And second of all I want to have something like this:
312: "0" 521: "1" 741: "2" 633: "0" 653: "8" 873: "4"
You guys have any idea of how I can do this?
Kind regards and thank you!
-
Jan over 5 yearsYeah, but then I still have arrays inside of the votes array. I want to have it linked directly without having arrays inside an array!
-
Zeeshan Ansari over 5 yearswould you like to send me the responseJson so I will give you a better solution for it thanks
-
Jan over 5 yearsThanks, that is what I was looking for!
-
Jan over 5 yearsLook at the answer below. That is what I was looking for. But thank you!