i can’t get array b of object a with reduce in js
can you help me find the error?
const a = {
dias:"valor",
horas:"valor"
}
const b = campos.reduce((acc, el) => ([...acc, {
title: el, field: el
}]), {})
desired result = [
{ title: 'dias', field: 'dias' },
{ title: 'horas', field: 'horas' },
]
Advertisement
Answer
You can use Object.keys().
const a = {
dias: "valor",
horas: "valor",
};
const b = Object.keys(a).map((key) => ({ title: key, field: key }));
console.log(b);If you want the value of the property as the field instead, you can use Object.entries():
const a = {
dias: "valor",
horas: "valor",
};
const b = Object.entries(a).map(([key, value]) => ({
title: key,
field: value,
}));
console.log(b);As a note, the [key, value] syntax is called array destructuring.