循环遍历2个数组和对象数组,并将数组1和数组2的元素插入对象的某些键的数组中

问题描述 投票:-1回答:1

我有一个对象数组和一个数组。我的意图是遍历这两者,并将数组的每个元素插入到对象数组的某个键中。

我打算动态插入每个数组的值

澄清说明:

  1. arr1长度= 44
  2. arr2长度= 44
  3. arrOfObj长度= 44
  4. 我的思考过程:

    1. 通过forEach或for通过arr1循环
    2. 循环通过arr2
    3. 通过arrOfObject循环
    4. 插入arrOfObject [i]。标签arr1 [i]
    5. 插入arrOfObject [i] .values arr2 [i]

示例:

  • 数组1
    const arr = [ 76, 72, 69, 66, 66, 66, 65, 65, 64, 64, 64, 63, 61, 61, 61, 61, 61, 61, 60, 59, 59, 59, 58, 58, 57, 57, 56, 56, 56, 55, 54, 54, 53, 52, 52, 51, 51, 50, 50, 49, 49, 49, 47, 47]
  • 数组2
    const arr2 = [ "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9", "Item10", "Item11", "Item12", "Item13", "Item14", "Item15", "Item16", "Item17","Item18", "Item19", "Item20", "Item21", "Item22", "Item23", "Item24", "Item25","Item26", "Item27", "Item28", "Item29", "Item30", "Item31", "Item32", "Item33", "Item34", "Item35", "Item36", "Item37", "Item38", "Item39", "Item40", "Item41", "Item42", "Item43", "Item44]
  • 对象数组
    const arrOfObj = [
    {
      labels:[],
      values: [],
    },
    {
      labels:[],
      values: [],
     },
    {
      labels:[],
      values: [],
     },
    ]

所需的输出是

    const arrOfObj = [
    {
      labels:[arr1[0]],
      values: [arr2[0]],
    },
    {
      labels:[arr1[1]],
      values: [arr2[1]],
     },
    ]

-结果

    const arrOfObj = [
    {
      labels:['item1'],
      values: [76],
    },
    {
      labels:['item2'],
      values: [72],
     },
    ]

如果有一种方法可以不使用嵌套循环(可能是一个循环用于插入值,一个单独的用于标签),因为嵌套循环会降低执行性能,因此除非有必要,否则最好这样做,否则就可以了。

同样,如果您是基础级别以上的对象和数组操作的良好来源,那么也很值得分享

非常感谢

javascript arrays object data-structures
1个回答
0
投票

只需在其中一个数组上使用map并获取索引作为callback的第二个参数。

const arrayObj = []
arr.map((ele, index) => {

    arrayObj.push(
        {
            labels: [arr[index]],
            values: [arr2[index]]
        }
    )
})

将所需的元素推到想要的数组上

© www.soinside.com 2019 - 2024. All rights reserved.