简体   繁体   中英

Re-structure using LODASH

I have been trying a few LoDash functions all day but couldn't get the right way to do this. Assigning a key fill to the parent array and also prepend with key levelno and each value of another array below [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 } ] ]

with [1,2,3,4,5] into this

{ '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
      }
    ]
  }]
}

Use vanilla js Array#map or lodash's _.map() to map each sub array to an object in the desired format:

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); 

The shorter ES6 version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM