new2coding
new2coding

Reputation: 37

Append to each item in array using Javascript

I have a code in JavaScript and i would like to append "i" to each item of the array inside the object. here is the code. Could anyone go through it and fix this code

    const forArray = [
    {
      username: "john",
      team: "red",
      score: 5,
      items: ["ball", "book", "pen"]
    },
    {
      username: "becky",
      team: "blue",
      score: 10,
      items: ["tape", "backpack", "pen"]
    },
    {
      username: "susy",
      team: "red",
      score: 55,
      items: ["ball", "eraser", "pen"]
    },
    {
      username: "tyson",
      team: "green",
      score: 1,
      items: ["book", "pen"]
    },
  
  ];

    const itemsArray = [];
    forArray.forEach(item => {
      let{items} = item;
      items = items + "i";
      itemsArray.push(items);
  })
  console.log(itemsArray);

Upvotes: 0

Views: 230

Answers (3)

osekmedia
osekmedia

Reputation: 683

Is this what you want? The code below will keep your original structure intact but append an i to the end of each element within the items array nested inside each object.

const forArray = [
    {
      username: "john",
      team: "red",
      score: 5,
      items: ["ball", "book", "pen"]
    },
    {
      username: "becky",
      team: "blue",
      score: 10,
      items: ["tape", "backpack", "pen"]
    },
    {
      username: "susy",
      team: "red",
      score: 55,
      items: ["ball", "eraser", "pen"]
    },
    {
      username: "tyson",
      team: "green",
      score: 1,
      items: ["book", "pen"]
    },
  
  ];

  forArray.map(item => item.items = item.items.map(i => i += 'i'));

Upvotes: 0

Sven.hig
Sven.hig

Reputation: 4519

You could use Map and append i to each element in the array and then use flat()to flatten the arrays

const forArray = [ { username: "john", team: "red", score: 5, items: ["ball", "book", "pen"] }, { username: "becky", team: "blue", score: 10, items: ["tape", "backpack", "pen"] }, { username: "susy", team: "red", score: 55, items: ["ball", "eraser", "pen"] }, { username: "tyson", team: "green", score: 1, items: ["book", "pen"] }, ];

    const itemsArray = [];
    forArray.forEach(item => {
      let{items} = item;
      itemsArray.push(items.map(o=>o+"i"))
  })
  console.log(itemsArray);

Upvotes: 0

User863
User863

Reputation: 20039

Using map()

const forArray = [{username:"john",team:"red",score:5,items:["ball","book","pen"]},{username:"becky",team:"blue",score:10,items:["tape","backpack","pen"]},{username:"susy",team:"red",score:55,items:["ball","eraser","pen"]},{username:"tyson",team:"green",score:1,items:["book","pen"]}];

const itemsArray = forArray.map(profile => 
  profile.items.map(item => item + 'i').join(',')
)
console.log(itemsArray);

Upvotes: 1

Related Questions