0

I'm trying to use destructuring but it seems I'm doing wrong the assignment.

Is it possible to do it like this?

  let fields = ["FASE", "BAWTOM_1"]
  let object = {}
  const d = await getData();

  const count = d.reduce((acc, elem) => {

     ({ [fields[0]], [fields[1]] }  = elem)
    return {...acc, [ fields[1] ]: [...(acc[ fields[1] ] || []), {fase: fields[0] }]};
}, {});

I'm stack on the ({ [fields[0]], [fields[1]] } = elem) that I'm not able to get it work

any help is much appreciated

elem is somthing like this, with much more items

var elem = [
{"FASE": "2",
"BAWTOM_1": "1",
"BA_SP_1": "0",
"BA_SP_2": "0",
"BA_SP_3": "0",
},
{"FASE": "1",
"BAWTOM_1": "2",
"BA_SP_1": "1",
"BA_SP_2": "0",
"BA_SP_3": "0",
},
{"FASE": "1",
"BAWTOM_1": "1",
"BA_SP_1": "0",
"BA_SP_2": "1",
"BA_SP_3": "0",
},
{"FASE": "2",
"BAWTOM_1": "4",
"BA_SP_1": "1",
"BA_SP_2": "0",
"BA_SP_3": "1",
}
]
b81
  • 69
  • 1
  • 10

2 Answers2

1

ok, got it.

here is the way I solved it. Of course it is not a production code, I'm just playing around but now I can translate it to somthing more usable

    async function pippo() {
  let fields = ["FASE", "BAWTOM_1"]
  let object = {}
  const d = await getData();


  const count = d.reduce((acc, elem) => {

     ({[fields[0]]: object[fields[0]], [fields[1]]: object[fields[1]]} = elem);
    return {...acc, [ object[fields[1]] ]: [...(acc[ object[fields[1]] ] || []), {fase: object[fields[0]] }]};
}, {});

console.log(count)
}
b81
  • 69
  • 1
  • 10
0

This won't work. The point of destructuring is to put the values into variables. Since you aren't creating variables it won't work. You can access the properties manually using indexing syntax as follows:

const fields0 = elem[fields[0]];
const fields1 = elem[fields[1]];

Hope that helps.

jack.benson
  • 2,211
  • 2
  • 9
  • 17
  • i'm trying to define it dinamically as described into this post https://dev.to/_bigblind/quick-tip-transform-an-array-into-an-object-using-reduce-2gh6 Probably I don't understand your answer becouse it don't work I'm also looking at this https://stackoverflow.com/questions/35939289/how-to-destructure-into-dynamically-named-variables-in-es6 – b81 Apr 01 '20 at 14:33
  • I don't really follow what you're trying to achieve with the code, BUT I will say, you should declare a function as async before using await, otherwise it won't work. Also, do a comb over at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment to learn all about destructuring. Objects are definitely a little stricter than arrays – Edgar Cuarezma Apr 01 '20 at 14:39
  • yes I know. I just copy a part of the code. It is all inside an async function. I'm just playng arounf with destructuring to better understand and than to split everything into two different function. Apart from async await my above code return an error inside the console log with the ',' in assignment. – b81 Apr 01 '20 at 14:43