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