2

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?

4
  • 1
    How are you providing the values for these keys? I mean, name='o1', name='02' etc. Are they random> Commented Mar 8, 2018 at 5:12
  • 1
    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'}. Commented Mar 8, 2018 at 5:15
  • This should be statement inside the loop a.push({id: ${i+1}, title: o${i+1}}); Commented Mar 8, 2018 at 6:34
  • @ivp the values are gonna be assigned in the loop from 1 to 5 Commented Mar 8, 2018 at 22:24

3 Answers 3

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.