📜  JavaScript 如何将二维数组转换为对象?

📅  最后修改于: 2022-05-13 01:56:30.778000             🧑  作者: Mango

JavaScript 如何将二维数组转换为对象?

在本文中,我们将学习如何将二维数组转换为对象。二维数组可以有任意数量的行和两列。

例子:

Input: [
         ["John", 12],
         ["Jack", 13],
         ["Matt", 14],
         ["Maxx", 15]
       ]

Output: {
          "John": 12,
          "Jack": 13,
          "Matt": 14,
          "Maxx": 15
        }

可以遵循以下方法来解决问题。

方法 1:在这种方法中,我们创建一个空对象并使用Array.forEach()方法对数组进行迭代。在每次迭代中,我们将子数组的第一项作为键插入到对象中,将第二项作为值插入到对象中。然后它在迭代后返回对象。

例子:

Javascript
function arr2obj(arr) {
  
    // Create an empty object
    let obj = {};
  
    arr.forEach((v) => {
  
        // Extract the key and the value
        let key = v[0];
        let value = v[1];
  
        // Add the key and value to
        // the object
        obj[key] = value;
    });
  
    // Return the object
    return obj;
}
  
console.log(
    arr2obj([
        ["John", 12],
        ["Jack", 13],
        ["Matt", 14],
        ["Maxx", 15],
    ])
);


Javascript
function arr2obj(arr) {
    return arr.reduce(
        (acc, curr) => {
              
            // Extract the key and the value
            let key = curr[0];
            let value = curr[1];
  
            // Assign key and value
            // to the accumulator
            acc[key] = value;
  
            // Return the accumulator
            return acc;
        },
  
        // Initialize with an empty object
        {}
    );
}
  
console.log(
    arr2obj([
        ["Eren", "Yeager"],
        ["Mikasa", "Ackermann"],
        ["Armin", "Arlelt"],
        ["Levi", "Ackermann"],
    ])
);


Javascript
function arr2obj(arr) {
  
    // Flatten the array
    arr = arr.flat();
  
    // Create an empty object
    let obj = {};
  
    for (let i = 0; i < arr.length; i++) {
        if (i % 2 == 0) {
  
            // Extract the key and the value
            let key = arr[i];
            let value = arr[i + 1];
  
            // Assign the key and value
            obj[key] = value;
        }
    }
  
    return obj;
}
  
console.log(
    arr2obj([
        ["Max", 19],
        ["Chloe", 20],
        ["Nathan", 22],
        ["Mark", 31],
    ])
);


输出:

{
  Jack: 13,
  John: 12,
  Matt: 14,
  Maxx: 15
}

方法 2:在这种方法中,我们将使用Array.reduce()方法并使用空对象初始化累加器。在每次迭代中,我们将当前值分配为累加器的键值并返回累加器。然后它在迭代后返回对象。

例子:

Javascript

function arr2obj(arr) {
    return arr.reduce(
        (acc, curr) => {
              
            // Extract the key and the value
            let key = curr[0];
            let value = curr[1];
  
            // Assign key and value
            // to the accumulator
            acc[key] = value;
  
            // Return the accumulator
            return acc;
        },
  
        // Initialize with an empty object
        {}
    );
}
  
console.log(
    arr2obj([
        ["Eren", "Yeager"],
        ["Mikasa", "Ackermann"],
        ["Armin", "Arlelt"],
        ["Levi", "Ackermann"],
    ])
);

输出:

{
  Eren: 'Yeager',
  Mikasa: 'Ackermann',
  Armin: 'Arlelt',
  Levi: 'Ackermann'
}

方法 3:在这种方法中,我们首先使用Array.flat( ) 方法将数组展平,从而得到一个一维数组。然后我们可以创建一个空对象并迭代数组以分配均匀定位的值作为对象的键和奇数定位的值作为值。

例子:

Javascript

function arr2obj(arr) {
  
    // Flatten the array
    arr = arr.flat();
  
    // Create an empty object
    let obj = {};
  
    for (let i = 0; i < arr.length; i++) {
        if (i % 2 == 0) {
  
            // Extract the key and the value
            let key = arr[i];
            let value = arr[i + 1];
  
            // Assign the key and value
            obj[key] = value;
        }
    }
  
    return obj;
}
  
console.log(
    arr2obj([
        ["Max", 19],
        ["Chloe", 20],
        ["Nathan", 22],
        ["Mark", 31],
    ])
);

输出:

{ 
  Max: 19,
  Chloe: 20, 
  Nathan: 22, 
  Mark: 31 
}