I need to get the minimum and maximum values of each of these objects within the following array. I've tried everything I know but the returned value is undefined, how can I do this? NOTE: Afterwards, I need to do the same in a constructor function and in a factory function. Is it the same procedure?
let faixas3 = [
{tooltip: 'de R$ 6667 até R$ 7777', minimo: 6667, maximo: 7777},
{tooltip: 'de R$ 7778 até R$ 8889', minimo: 7778, maximo: 8889},
{tooltip: 'de R$ 9000 até R$ 10000', minimo: 9000, maximo: 10000}
];
const {tooltip, minimo, maximo} = faixas3;
console.log({tooltip, minimo, maximo}); // { tooltip: undefined, minimo: undefined, maximo: undefined }
console.log(tooltip, minimo, maximo); // undefined undefined undefined
You have an array of objects. To destructure values as you're doing in the example, you have to specify from which index you want to destructure values from.
const {tooltip, minimo, maximo} = faixas3[0];
const {tooltip, minimo, maximo} = faixas3[1];
const {tooltip, minimo, maximo} = faixas3[2];
or you can use a loop for looping over the elements.
You can try this.
function column(array, columnName) {
return array.map(function(value,index) {
return value[columnName];
})
}
const {tooltip, minimo, maximo} = [column(faixas3,'tooltip'),column(faixas3,'minimo'),column(faixas3,'maximo')];
You can 'redefine' faixas3 in several ways using Array.map. Here are two examples. The first map-result is used to declare variables with destructuring.
const logElem = document.querySelector(`pre`);
const faixas3 = [
{tooltip: 'de R$ 6667 até R$ 7777', minimo: 6667, maximo: 7777},
{tooltip: 'de R$ 7778 até R$ 8889', minimo: 7778, maximo: 8889},
{tooltip: 'de R$ 9000 até R$ 10000', minimo: 9000, maximo: 10000}
];
const faixas_minmax1 = faixas3.map(v => [v.minimo, v.maximo]);
logElem.textContent = `faixas_minmax1: ${JSON.stringify(faixas_minmax1)}`;
const faixas_minmax2 = faixas3.map(v => ({min: v.minimo, max: v.maximo}));
logElem.textContent += `\nfaixas_minmax2: ${
JSON.stringify(faixas_minmax2, null, 2)}`;
// destructuring assignment to variables from faixas_minmax1
const [f3min0, f3max0, f3min1, f3max1, f3min2, f3max2] = faixas_minmax1.flat();
logElem.textContent += `\nf3min0, f3max2: ${f3min0}, ${f3max2}`;
<pre></pre>