Q:

formatting data in new structure

I've at the moment 1 array with labels and 2 objects with keys and values. 
With this data i want to format a new array with object. 
Example:
const years = ["5", "6", "7", "8", "9"];
const left = {5: 2, 6: 1, 7: 22};
const right = {6: 1, 7: 1, 8: 22, 9: 1};

//Output should be
const newArr = [
    {
        label: 5 year,
        left: 2,
        right: null,
    },
    {
        label: 6 year,
        left: 1,
        right: 1,
    },
    {
        label: 7 year,
        left: 22,
        right: 1,
    },
    {
        label: 8 year,
        left: null,
        right: 22,
    },
    {
        label: 9 year,
        left: null,
        right: 1,
    },
]

if one of the object doesn't have the year(key) in object this value is null. 

A:

Use map
var replaceFn = ( obj, key ) => ! obj.hasOwnProperty( key ) ?  null : obj[ key ]; 

var output = years.map( s => ({ 
         label : s + " years", 
         left : replaceFn( left, s ), 
         right : replaceFn( right, s ) 
}));

Demo

var years = ["5", "6", "7", "8", "9"];
var left = {5: 2, 6: 1, 7: 22, 8: undefined};
var right = {6: 1, 7: 1, 8: 22, 9: 1};

console.log( left.hasOwnProperty( 8 ) );

var replaceFn = ( obj, key ) => ! obj.hasOwnProperty( key ) ?  null : obj[ key ]; 

var output = years.map( s => ({ 
         label : s + " years", 
         left : replaceFn( left, s ), 
         right : replaceFn( right, s ) 
}));

console.log( output );

