W'hales Sean George W'hales Sean George - 8 days ago 4
Javascript Question

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

Answer

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