如何在typescript中生成动态对象数组

时间:2018-03-08 05:11:03

标签: javascript arrays 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;
}

想法?

3 个答案:

答案 0 :(得分:2)

您没有提供太多信息,但这应该适合您。

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

答案 1 :(得分:1)

  

这应该这样做

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

只需尝试

type Obj = {[key: number]: number}
function getItems(names: number[]) {

  const arr: Obj[] = []; // your array is an array of Obj Type

  for (let i = 0; i < 5; i++) {
    // obj also is of type Obj
    const obj = names.reduce((acc, val) => {
      acc[val] = val + i
      return acc;
    }, {} as Obj)
    // here you can push obj in your array
    arr.push(obj);
  }
  return arr;
}