使用LODASH重新构造

时间:2016-11-30 12:29:21

标签: javascript arrays lodash

我整天都在尝试一些LoDash功能,但无法通过正确的方式完成此操作。将键fill分配给父数组,并使用键levelno[1,2,3,4,5]下面的另一个数组的每个值前置

[ [ { rect: 'R202',
   x: 163,
   y: 1393,
   width: 38,
   height: 17.5,
   grade: 'hf',
   accessible: false },
 { rect: 'R214',
   x: 163,
   y: 1445.5,
   width: 38,
   height: 17.5,
   grade: 'hf',
   accessible: false } ],
[ { rect: 'R202',
   x: 163,
   y: 1393,
   width: 38,
   height: 17.5,
   grade: 'hf',
   accessible: false },
 { rect: 'R214',
   x: 163,
   y: 1445.5,
   width: 38,
   height: 17.5,
   grade: 'hf',
   accessible: false } ] ]

[1,2,3,4,5]进入此

{ 'level: [{
    "levelno": 1,
    "fill": [
      { 
        rect: "R202",
        x: 163,
        y: 1393,
        width: 38,
        height: 17.5,
        grade: "hf",
        accessible: false 
      }, {
        rect: "R214",
        x: 163,
        y: 1445.5,
        width: 38,
        height: 17.5,
        grade: "hf",
        accessible: false
      }
    ]
  }, {
    "levelno": 2,
    "fill": [
      { 
        rect: "R202",
        x: 163,
        y: 1393,
        width: 38,
        height: 17.5,
        grade: "hf",
        accessible: false 
      }, {
        rect: "R214",
        x: 163,
        y: 1445.5,
        width: 38,
        height: 17.5,
        grade: "hf",
        accessible: false
      }
    ]
  }]
}

1 个答案:

答案 0 :(得分:3)

使用vanilla js Array#map或lodash的_.map()将每个子数组映射到所需格式的对象:

function level(data, levels) {
  return {
    level: data.map(function(fill, index) {
       return {
         levelno: levels[index],
         fill: fill
       };
    })
  }; 
}

function level(data, levels) {
  return {
    level: data.map(function(fill, index) {
       return {
         levelno: levels[index],
         fill: fill
       };
    })
  }; 
}

var data = [
  [{
    rect: 'R202',
    x: 163,
    y: 1393,
    width: 38,
    height: 17.5,
    grade: 'hf',
    accessible: false
  }, {
    rect: 'R214',
    x: 163,
    y: 1445.5,
    width: 38,
    height: 17.5,
    grade: 'hf',
    accessible: false
  }],
  [{
    rect: 'R202',
    x: 163,
    y: 1393,
    width: 38,
    height: 17.5,
    grade: 'hf',
    accessible: false
  }, {
    rect: 'R214',
    x: 163,
    y: 1445.5,
    width: 38,
    height: 17.5,
    grade: 'hf',
    accessible: false
  }]
];

var levels = [1, 2, 3, 4, 5];
var result = level(data, levels);

console.log(result);

较短的ES6版本:

const level = (data, levels) => ({
  level: data.map((fill, index) => ({
    levelno: levels[index],
    fill
  }))
});