Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

JavaScript - how to convert json to dictionary from server response?

0 contributions
3 points

As first it is good to read this article too.

1. Problem description

Conversion from server response:

{
   "result" : true,
   "people" : [
      { "id": 5,  "name": "John" },
      { "id": 21, "name": "Denis" },
      { "id": 59, "name": "Chris" }
   ]
}

To JavaScript people dictionary object with id as key.

2. Problem solution

// ONLINE-RUNNER:browser;

// response from server

var jsonResponse = '' +
    '{\n' +
    '   "result" : true,\n' +
    '   "people" : [\n' +
    '      { "id": 5,  "name": "John" },\n' +
    '      { "id": 21, "name": "Denis" },\n' +
    '      { "id": 59, "name": "Chris" }\n' +
    '   ]\n' +
    '}';

var objectResponse = JSON.parse(jsonResponse);

// array to dictionary conversion

var peopleArray = objectResponse.people;
var peopleDictionary = { };

for (var i = 0; i < peopleArray.length; ++i) {
    var entry = peopleArray[i];

    peopleDictionary[entry.id] = entry;
    //peopleDictionary[entry.id] = entry.name;
}

// result printing

console.log(peopleDictionary[21].id);
console.log(peopleDictionary[21].name);

See also

  1. https://dirask.com/q/javascript-deserialize-json-to-object-Ej4Oxp

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more