我现在有一个带有标签的数组和带有键和值的2个对象。 有了这些数据,我想用对象格式化一个新数组。
示例:
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,
},
]
如果其中一个对象没有对象中的year(key),则该值为null。
答案 0 :(得分:4)
使用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 )
}));
<强>演示强>
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 );
&#13;
答案 1 :(得分:1)
只需遍历years数组并动态获取其他两个对象的值:
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};
const newArr = [];
years.forEach(year => {
newArr.push({
label: `${year} year(s)`,
right: right[year] || null,
left: left[year] || null,
})
});
答案 2 :(得分:0)
您可以检查密钥是否在对象(in
operator)中并取值,否则取null
。
var years = ["5", "6", "7", "8", "9"],
left = { 5: 2, 6: 1, 7: 22 },
right = { 6: 1, 7: 1, 8: 22, 9: 1 },
result = years.map(k => ({
label: k + ' year',
left: k in left ? left[k] : null,
right: k in right ? right[k] : null
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }