我正在以对象形式接收数据。该对象包含三个键保存数组值的属性。我想将这三个数组连接成一个主Array
。但应该按照首选顺序。像
var obj = {'type':['a','b'],'power':[500,700],'make':['2012','2015']}
oneArray(obj,'make','type','power')
主人Array
应首先从对象获得'make','type'然后'power'键Array
。现在它正按顺序排列obj
Fidde
var obj = {'type':['a','b'],'power':[500,700],'make':['2012','2015']}
var oneArray = function (obj,first,second,third){
var newObj = obj;
var list = [];
for(var key in newObj){
if (newObj[key] instanceof Array) {
if (!list) {
list = newObj[key];
}
else {
list = list.concat(newObj[key]);
}
}
}
newObj['all'] = list;
return newObj
}
console.log(oneArray(obj,'make','type','power'))
答案 0 :(得分:0)
我不确定我是否明白你的问题,但试试这个...... 这个onArray()函数接受的参数以有序的方式指示优先级,但第一个参数。
var obj = {'type':['a','b'],'power':[500,700],'make':['2012','2015']}
var oneArray = function(obj) {
var newObj = obj;
var list = [];
var priorityList = arguments;
for( var i = 1 ; i < priorityList.length ; i++ ) {
if( newObj[ priorityList[i] ] instanceof Array ) {
for( var key in newObj[ priorityList[i] ] ) {
list.push( newObj[ priorityList[i] ][ key ] );
}
}
}
newObj['all'] = list;
return newObj;
}
console.log(oneArray(obj,'make','type','power'));