轉換的最佳方法是什么:
["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()
但我不確定如何構建我的映射功能。任何見解都會有所幫助。
uj5u.com熱心網友回復:
我認為您可以執行以下操作
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);
uj5u.com熱心網友回復:
您可以使用以下功能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; }
uj5u.com熱心網友回復:
你的 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"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448353.html
標籤:javascript 数组 json 目的 反应打字稿
上一篇:python中物件的同名
