Sergino
Sergino

Reputation: 10818

How to generate dynamic array of objects in typescript

I want to pass the array of string names in to the function and be able to generate the array of objects based on that.

Say I am passing { 'id', 'title' } and as an output I am getting

[
    {
      id: '1',
      title: 'o1'
    },
    {
      id: '2',
      title: 'o2'
    },
]

I am kind of stucked as not sure how would you take the array of stirngs and convert its elements in to an object

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

thoughts?

Upvotes: 2

Views: 28598

Answers (3)

user3550446
user3550446

Reputation: 455

just try this

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

Upvotes: 0

Abhijit Kar ツ
Abhijit Kar ツ

Reputation: 1732

This should do it

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

Upvotes: 3

Gokul Chandrasekaran
Gokul Chandrasekaran

Reputation: 545

You have not provided much information, but this should work for you.

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

Upvotes: 5

Related Questions