将 table 架构的数组转换为对象

Convert Array to Object for table Schema

最好的转换方式是什么:

["Foo", "Bar", "John"]

收件人:

{
Foo: { name: 'Foo', index: 0, type: 'String' },
Bar: { name: 'Bar', index: 1, type: 'String' },
John: { name: 'John', index: 2, type: 'String' },
}

我认为我需要利用

array.map()

但我不确定如何构造我的映射函数。任何见解都会有所帮助。

您可以Array.prototype.reduce 的功能如下。

const source = ["Foo", "Bar", "John"],
  capitalize = string => string.charAt(0).toUpperCase() + string.slice(1),
  result = source.reduce((a, name, index) => ({...a, [name]: {name, index, type: capitalize(typeof name)}}), {});
  
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

你的 json 无效,所以如果你需要这样的有效 json

[{"name":"Foo","index":0,"type":"string"},{"name":"Foo","index":1,"type":"string"},{"name":"Foo","index":2,"type":"string"}]

您可以使用此代码

var result=[];
arr.forEach( (element,i )=> {
  result.push( {name:element, index:i, type: typeof element});
 });

更新

为了你的另一个 json

var jarr=["Foo", "Bar", "John"]

您可以使用此代码

var result = {};
jarr.forEach((element, i) => {
  result[element] = { name: element, index: i, type: typeof element };
});

结果

{
  "Foo": {
    "name": "Foo",
    "index": 0,
    "type": "string"
  },
  "Bar": {
    "name": "Bar",
    "index": 1,
    "type": "string"
  },
  "John": {
    "name": "John",
    "index": 2,
    "type": "string"
  }
}

我想你可以按如下方式做

const array = ["Foo", "Bar", "John"];
Object.fromEntries(
   array
   .map((el, index) => {
     return [el, {name: el, index, type: el.constructor.name}]
   })
)

在这里您可以找到一个示例片段:

const array = ["Foo", "Bar", "John"];
const result = Object.fromEntries(
   array
   .map((el, index) => {
     return [el, {name: el, index, type: el.constructor.name}]
   })
);
console.log(result);