简体   繁体   English

将值数组映射到对象数组

[英]Mapping an array of values to an array of objects

So I have an issue that requires me to map an array of names to an object with a property of name.所以我有一个问题,需要我将一个名称数组 map 转换为一个具有名称属性的 object。

The following code is in question:以下代码有问题:

this.planNames.map((name,index) => {
     this.tempdata[index].name = name;
        }),

Here is an example of the array.这是数组的一个示例。

tempdata: any = [
    {
      name: 'Mix and match',
      title: 'Single-line plans for voice messaging and data.',
      desc:
        'A great plan option for businesses that want each line on its own plan. These plans have no maximum line caps.',
    },
    {
      name: 'Flexible',
      title: 'Multi-line plans for when one size does not fit all.',
      desc:
        'A great plan option for up to 10 phones with different unlimited data needs',
    }

Any idea using arrow functions would be great as I am learning more about these myself.任何使用箭头函数的想法都会很棒,因为我自己正在学习更多关于这些的知识。

There should be some changes in your map function.您的 map function 应该有一些变化。

this.planNames.map((item,index) => {
   this.tempdata[index].name = item.name;
});
console.log(this.tempData)

The map function is only to replace data by others in array. map function 仅用于替换数组中的其他数据。
If you want to update other array data, you should use a for loop:如果要更新其他数组数据,则应使用for循环:

 const tempdata = [ { name: 'Mix and match', title: 'Single-line plans for voice messaging and data.', desc: 'A great plan option for businesses that want each line on its own plan. These plans have no maximum line caps.', }, { name: 'Flexible', title: 'Multi-line plans for when one size does not fit all.', desc: 'A great plan option for up to 10 phones with different unlimited data needs', } ]; const planNames = ['a', 'b']; for(let i = 0; i < planNames.length; i++) { tempdata[i].name = planNames[i]; } console.log(tempdata);

[].map returns a new array containing the result of each of the original array elements passed through the callback function. [].map返回一个新数组,其中包含通过回调 function 传递的每个原始数组元素的结果。 So, you don't need to create a temporary array beforehand - the result of the map function will contain what you need.因此,您无需事先创建临时数组 - map function 的结果将包含您需要的内容。

const newTempData = this.planNames.map((name, index) => {
   return { ...tempdata[i], name }
});

You don't generally mutate data in a .map function.您通常不会.map function 中的数据。 If you're interested in mutating the original data structure, tempdata , you should just use a standard [].forEach .如果您对改变原始数据结构tempdata感兴趣,您应该只使用标准的[].forEach

tempdata.forEach((data, index) => {
    data.name = this.planNames[index];
});

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

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