How to generate dynamic array of objects in typescript

14,581

Solution 1

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

Solution 2

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

Share:
14,581
sreginogemoh
Author by

sreginogemoh

Updated on June 15, 2022

Comments

  • sreginogemoh
    sreginogemoh almost 2 years

    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?

    • ivp
      ivp about 6 years
      How are you providing the values for these keys? I mean, name='o1', name='02' etc. Are they random>
    • Hussain Ali Akbar
      Hussain Ali Akbar about 6 years
      yup. You need to tell us how the values will be assigned to the properties? Also an array would be ['id', 'title'] not {'id', 'title'}.
    • Hassan Imam
      Hassan Imam about 6 years
      This should be statement inside the loop a.push({id: ${i+1}, title: o${i+1}});
    • sreginogemoh
      sreginogemoh about 6 years
      @ivp the values are gonna be assigned in the loop from 1 to 5
  • Mohammad Atiour Islam
    Mohammad Atiour Islam about 3 years
    Thank you @Abhijit