const obj = {
a: "day1",
b: "",
c: "day3",
aa: 10,
bb: 11,
cc: 12,
}
const items = [];
// slightly fixed OP approach.
for (const key in obj) {
if (key === 'a') {
items.push({
title: obj.a,
value: obj.aa,
});
}
if (key === 'b') {
items.push({
title: obj.b,
value: obj.bb,
});
}
if (key === 'c') {
items.push({
title: obj.c,
value: obj.cc,
});
}
}
console.log({ items });
// or entirely generic/configurable and maybe even more expressive ...
console.log(
Object
.entries(obj)
.reduce(({ target, valueMap, result }, [key, value]) => {
if (key in valueMap) {
result.push({
title: value,
value: target[valueMap[key]],
});
}
return { target, valueMap, result };
}, {
target: obj,
valueMap: { a: 'aa', b: 'bb', c: 'cc' },
result: [],
}).result
);
.as-console-wrapper { min-height: 100%!important; top: 0; }