简体   繁体   English

Append 使用 Javascript 到数组中的每个项目

[英]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.我在 JavaScript 中有一个代码,我想将 append “i”添加到 object 中的每个数组项。 here is the code.这是代码。 Could anyone go through it and fix this code任何人都可以通过它 go 并修复此代码

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

Using map()使用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);

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.下面的代码将保持原始结构不变,但 append 和 i 到嵌套在每个 object 内的 items 数组中每个元素的末尾。

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

You could use Map and append i to each element in the array and then use flat() to flatten the arrays您可以使用 Map 和 append i到数组中的每个元素,然后使用flat()来展平 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM