javascript - 如何在 typescript 中生成動態物件陣列
我想將字串陣列 names 傳入函式中,並能夠基於它生成物件陣列。
說我正在傳遞 { 'id', 'title' },並且作為輸出我得到
[
{
id: '1',
title: 'o1'
},
{
id: '2',
title: 'o2'
},
]
我有點卡住了,不確定你會如何將字串陣列的元素轉換成物件
export function getItems(names) {
const a: any[] = [];
for (let i = 0; i < 5; i++) {
// need to produce 5 objects here like:
// {
// id: '1',
// title: 'o1'
// }
a.push(object);
}
return a;
}
想法?
答案#1
你沒有提供太多資訊,但這應該對你有用。
function getItems(names) {
const a: any[] = [];
for (let i = 0; i < 5; i++) {
a.push(names.reduce((acc, val) => {
acc[val] = val + i
return acc
}, {}));
}
return a;
}
答案#2
這應該可以了
function manufactureArray(props, num) {
var arr = [];
var obj;
// Loop for the number of objects you want to push to the array
for (var i = 0; i < num; i++) {
obj = {};
// Create the properties within a new object, and push it into the array
for (var j = 0; j < props.length; j++) {
// Using square bracket creates a property,
// so this line will become: obj["id"] = "0 0" and so on
obj[props[j]] = i + " " + j;
}
arr.push(obj);
}
return arr;
}
var num = prompt("Enter array length");
var arr = manufactureArray(['id', 'title'], num);
console.log(arr);