在 JavaScript 中将数据从嵌套数组转换为对象

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 17:16:17

假设,我们有以下数组 −

const arr = [
   [
      ['dog', 'Harry'], ['age', 2]
   ],
   [
      ['dog', 'Roger'], ['age', 5]
   ]
];

我们需要编写一个 JavaScript 函数,该函数接受一个这样的嵌套数组。然后该函数应根据该数组准备一个对象。

上述数组的对象应如下所示 −

const output = [
   {dog: 'Harry', age: 2},
   {dog: 'Roger', age: 5}
];

示例

其代码为 −

const arr = [
   [
      ['dog', 'Harry'], ['age', 2]
   ],
   [
      ['dog', 'Roger'], ['age', 5]
   ]
];
const prepareObjectArray = (arr = []) => {
   const copy = arr.slice();
   copy.forEach((el, ind, array) => {
      el.forEach((element, index, subArray) => {
         subArray[element[0]] = element[1];
      });
      el.length = 0;
      array[ind] = Object.assign({}, array[ind]);
   });
   return copy;
};
console.log(prepareObjectArray(arr));

输出

控制台中的输出将是 −

[ { dog: 'Harry', age: 2 }, { dog: 'Roger', age: 5 } ]

相关文章


有用资源