【问题标题】:Creating objects from arrays and collecting these objects in a one array [closed]从数组创建对象并将这些对象收集在一个数组中[关闭]
【发布时间】:2021-04-21 07:38:18
【问题描述】:

我想学习这个任务解决方案

如何将两个数组都添加到对象中并将它们添加到新数组中?

nameList = ["Jhon", "Mohammad", "Peter", "Harry"];
ageList = ["21", "27", "35", "65"];

var arr = [
{
    "name" : "Jhon",
    "age" : "21"
},
{
    "name" : "Mohammad",
    "age" : "27"
},
{
    "name" : "Peter",
    "age" : "35"
},
{
    "name" : "Harry",
    "age" : "65"
}
]

【问题讨论】:

  • 请注意,这不是一个“请教我”的网站。您应该至少自己尝试一下,并在您的问题中提出。 How to Ask.
  • 到目前为止你尝试过什么?到现在为止,你应该给我们你的努力。
  • 你永远是对的。很高兴听到您的这些规则。我将在下一篇文章中尝试关注这一点。谢谢
  • 这能回答你的问题吗? Combine the values of two arrays into object
  • 是的。 @NguyễnVănPhong 的回答也足够了。非常感谢

标签: javascript


【解决方案1】:

如果两个数组的长度相同,可以这样使用Array#map

const nameList = ["Jhon", "Mohammad", "Peter", "Harry"];
const ageList = ["21", "27", "35", "65"];

const result = nameList.map((r, index) => ({name: r, age: ageList[index]}));
console.log(result);

如果长度不同,可以这样试试

const nameList = ["Jhon", "Mohammad", "Peter", "Harry"];
const ageList = ["21", "27", "35"]; // <-- missing age of Harry

let nLength = nameList.length , aLength = ageList.length, index = 0;
const result = [];
while(index < nLength && index < aLength){
  result.push({name: nameList[index], age: ageList[index]});
  index++;
}
console.log(result);

【讨论】:

    【解决方案2】:
    nameList = ["Jhon", "Mohammad", "Peter", "Harry"];
    ageList = ["21", "27", "35", "65"];
    var arr = [];
    
    for(let i=0; i<nameList.length;i++){
    arr.push({
       name: nameList[i],
       age: ageList[i]
    })
    }
    
    

    【讨论】:

      猜你喜欢
      • 2018-08-20
      • 2021-03-30
      • 2023-02-09
      • 2021-07-12
      • 2011-08-29
      • 1970-01-01
      • 2019-09-23
      • 2019-04-08
      • 1970-01-01
      相关资源
      最近更新 更多