3

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 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that is what I was looking for!
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);

3 Comments

Yeah, but then I still have arrays inside of the votes array. I want to have it linked directly without having arrays inside an array!
would you like to send me the responseJson so I will give you a better solution for it thanks
Look at the answer below. That is what I was looking for. But thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.