React Native: Key Value array or hasmap?

Viewed 13902

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!

2 Answers

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.

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);
Related