从另一个 JSON 对象开始为 Materialise 自动完成创建 JSON 对象

Create JSON object starting from another JSON Object for Materialize Autocomplete

我正在尝试使用 Materialise 的自动完成功能。

API 请求提供以下数据:

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

]

但我需要使用 JavaScript 格式化此数据,如下所示:

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

提前感谢您的帮助! :)

您可以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 (...)。

参见下面的示例:

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

您为此要做的就是将每个名称分配为新对象中的键:

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