0

I'm trying to work with autocomplete from Materialize.

The API Request provides following data:

[
    {
       "id": 4007,
       "name": "Curitiba, Paraná, BR"
    },
    {
       "id": 4391,
       "name": "Curitibanos, Santa Catarina, BR"
    }

]

But I need format this data using JavaScript in something that looks like:

{ 
  "Curitiba, Paraná, BR": null,
  "Curitibanos, Santa Catarina, BR" , null
}

Thank you in advance for any help! :)

drmwndr
  • 94
  • 8

2 Answers2

1

You can map your array of objects to an array of {[name]: null} objects. Here [name] is a computed property name, which allows you to use the value of the name variable as the key for your object. You can then merge the mapped array into one resulting object using Object.assign() along with the spread syntax (...).

See example below:

const arr= [ { "id": 4007, "name": "Curitiba, Paraná, BR" }, { "id": 4391, "name": "Curitibanos, Santa Catarina, BR" } ];

const res = Object.assign(...arr.map(({name}) => ({[name]: null})));
console.log(res);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
1

All you have to do for this is to assign each name as a key in a new object:

const data = [
    {
       "id": 4007,
       "name": "Curitiba, Paraná, BR"
    },
    {
       "id": 4391,
       "name": "Curitibanos, Santa Catarina, BR"
    }

];

var object = {};
var i = 0;

for (i = 0; i < data.length; i++) {
    object[data[i].name] = null;
};

console.log(object);
sbgib
  • 5,580
  • 3
  • 19
  • 26
  • 1
    Awesome answer, Works like a charm, for me that are so not skilled with Javascript, that allowed me to clear see the logic behind operation. Anyway, in console looks like its returning Curitiba, Paraná, BR: null instead "Curitiba, Paraná, BR": null is this only a formating by inspector or this is expected? Thank you. – drmwndr Oct 16 '20 at 19:26
  • 1
    Thank you :) I think that's just formatting - you can prove it to yourself by doing `console.log(JSON.stringify(object));`. As well as being clearer to understand, simply using a `for` loop is also more efficient than these newer in-built functions (no function calls needed), so this typically seems like the best practice. – sbgib Oct 17 '20 at 09:25