js根据相同属性值将一个一维对象数组转为二维数组

2021-06-19  本文已影响0人  阳光之城alt

1 将一个一维对象数组,根据相同的属性值,转化成一个二维数组

// 待转换的一维数组
var arrayFirst = [{
    code: 1,
    datas: 'a网吧'
},
{
    code: 1,
    datas: 'b网吧'
}, {
    code: 2,
    datas: 'a酒店'
},
{
    code: 2,
    datas: 'b酒店'
},
{
    code: 3,
    datas: 'a学校'
}, {
    code: 3,
    datas: 'b学校'
},
{
    code: 3,
    datas: 'c学校'
}
]

按照相同的code值转换成二维数组

// 转换后的二维数组
[
[{code: 1, datas: "a网吧"},{code: 1, datas: "b网吧"}],
[{code: 2, datas: "a酒店"},{code: 2, datas: "b酒店"}], 
[{code: 3, datas: "a学校"},{code: 3, datas: "b学校"},{code: 3, datas: "c学校"}]]
————————————————

es6的方法
使用es6的方法
Object.values() //返回 值 数组
返回数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值

// 转换后的二维数组
var arrayTwo = Object.values(arrayFirst.reduce((res, item) => {
  res[item.code] ? res[item.code].push(item) : res[item.code] = [item];
  return res;
}, {}));
console.log(arrayTwo)

第二种方法

/ 转换后的二维数组
function convert (arr) {
    var map1 = {};
    while(arr.length) {
        let current = arr.pop(); // 会影响原数组
        map1[current.code] = map1[current.code] || [];
        map1[current.code].push(current);
    }
    
    return Object.keys(map1).map(key => map1[key]);
}
var arrayTwo = convert(arrayFirst)
console.log(arrayTwo)

2 以上是一个具有相同code值的一维数组,需要转换成如下的二维数组

let arr = [
      {code: "China", name: "xiaohuai"},
      {code: "Africa", name: "neiLuoBi"},   
      {code: "Asia", name: "hanGuo"},
      {code: "China", name: "tnnyang"},
      {code: "Africa", name: "nanFei"},      
      {code: "China", name: "yangMan"}
]
 
var map = new Map();
var newArr = [];
arr.forEach(item => {
     map.has(item.code) ? map.get(item.code).push(item) : map.set(item.code, [item]);
})
 
newArr = [...map.values()];
    
console.log(newArr);

实现了一维数组转二维,那么再将转换后的二维数组转换为一维数组呢?还是直接上代码吧:

let arr = [
    [ {code: "China", name: "xiaohuai"}, {code: "China", name: "tnnyang"}, {code: "China", name: "yangMan"} ],
    [ {code: "Africa", name: "neiLuoBi"}, {code: "Africa", name: "nanFei"} ],
    [ {code: "Asia", name: "hanGuo"} ]  
]
 
//方法一:
function reduceDimension(arr) {
      var reduced = [];
      for (var i = 0; i < arr.length; i++) {
          for (var j = 0; j < arr[i].length; j++) {
              reduced.push(arr[i][j]);
          }
      }
      return reduced;
}
 
console.log(reduceDimension(arr));
 
//方法二:
console.log([].concat.apply([], arr));

1 原文地址https://blog.csdn.net/qq_39840470/article/details/88184538

2 https://blog.csdn.net/weixin_34365635/article/details/93612598?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-6.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-6.control

上一篇下一篇

猜你喜欢

热点阅读