Home > Blockchain >  Convert incoming string to dictionary/map javascript
Convert incoming string to dictionary/map javascript

Time:09-13

I am new javascript. I could do this in 2 seconds in python/java but I am struggling here. I am developing an reactJS app. I am retrieving a string which is a dictionary/HashMap<String, ArrayList> from a server via axios. I get response.data and my data is in the form:

{ "key1": [1,23,4,5,5,2], 
   "key2": [2,6,5,5,5,6,5],
   ...
}

I want to convert this into a map/dictionary so I can access it like so (get(), keys(), etc.

However, i am having trouble doing this. console.log(typeof data) gives me string.

And when I JSON.parse() or JSON.stringify() and use new Map() i get this weird thing with thousands of integer keys and it doesn't act like I want. Any idea on how I can do this?

Thanks!


EDIT

Here is a more complete code example.

const fetchData = () => {
    const url = "http://127.0.0.1:8081/pdata";
    const promise = axios.get(url);
    console.log(promise);
    const dataPromise = promise.then((response) => response.data);
    console.log(dataPromise);

    return dataPromise;
}
export default function Home() {

  //Bind the data to a useState Hook in React, to ensure that we have the correct data
  const [data, setData] = React.useState([]);

  //This function runs on page reload, twice. Your fetch data function will run repeatedly while contained 
  //within this functional component.
  useEffect(() => {
    fetchData().then((apiEndpoint) => {
      //setting data equal to the result of the FetchData function
      setData(apiEndpoint);
    }).catch(err => console.log(err))
  }, [])

  // We now have the data. 
  // Convert it to a map
  const map = new Map(Object.entries(data));
  console.log(map.get("Model Used"));
  console.log([...map.keys()]);

At point We now have the data, console.log(data) prints the incoming data correctly its just is of type string not map or whatever javascript calls it.

CodePudding user response:

Using Map and Object#entries:

const obj = { "key1": [1,23,4,5,5,2], "key2": [2,6,5,5,5,6,5] };

const map = new Map(Object.entries(obj));

console.log(map.get("key1"));
console.log([...map.keys()]);

CodePudding user response:

From https://flexiple.com/javascript/javascript-dictionary/

Are there dictionaries in JavaScript? No, as of now JavaScript does not include a native “Dictionary” data type. However, Objects in JavaScript are quite flexible and can be used to create key-value pairs. These objects are quite similar to dictionaries and work alike.

It seems you can just parse the string that you obtained to JSON and use the parsed object obtained. For example:

var api_response = `
{ 
    "key1": [1,23,4,5,5,2], 
    "key2": [2,6,5,5,5,6,5]
}`;

var parsed_data = JSON.parse(api_response);

console.log(Object.keys(parsed_data))
console.log(parsed_data["key2"])
console.log(parsed_data.key1)

  • Related