本文介绍了如何将嵌套数组对转换为数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的任务是将以下数组转换为对象对数组:
var arr = [[['名字','乔'],['姓氏','吹'],['年龄', 42],['角色','职员'],[['名字','玛丽'],['姓氏','詹金斯'],['年龄', 36],['角色','经理']]]]
我需要将 arr
转换成如下所示的对象数组:
解决方案
程序化解决方案(也可在 https://jsfiddle.net/edorka/jnLxyzhb/):
var arr = [[ ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],[['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ]];var 空 = {};var 结果 = arr.map(function(objectArray){var object = this;var 属性 = objectArray.map(function(attrArray){var name = attrArray[0], value = attrArray[1];对象[名称] = 值;返回对象;}, 目的);返回这个;}, 空的);控制台日志(结果);
I have been tasked to convert the following array to an array of object pairs:
var arr = [
[
['firstName', 'Joe'],
['lastName', 'Blow'],
['age', 42],
['role', 'clerk'],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
]
]
I need to transform arr
into an array of objects that looks like this:
[
{firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
{firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]
解决方案
Programmatic solution (available too at https://jsfiddle.net/edorka/jnLxyzhb/):
var arr = [[ ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ]];
var empty = {};
var result = arr.map(function(objectArray){
var object = this;
var attribute = objectArray.map(function(attrArray){
var name = attrArray[0], value = attrArray[1];
object[name] = value;
return object;
}, object);
return this;
}, empty);
console.log(result);
这篇关于如何将嵌套数组对转换为数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!