1

I Initialize the empty variables first

let a = "";
let b = "";
let c = "";

Then call the api and after getting data assign the values from api response to the variables. If not getting any data then this will be empty.

suppose dataArray is the array where I am getting the response.

So, what I have done is:

dataArray = dataArray.map((x) => {
  a = x.valueA;
  b = x.valueB;
  c = x.valueC;
});

Everything is fine on my response and code but when I check through ESLINT it return the error that is Use object destructuring Is there anyone who help me to fix out this things. Any support is really appreciated

Aks
  • 1,092
  • 3
  • 12
  • 29
  • 1
    Are you sure `dataArray` is array object like `[{}]`?. Because if you are using map on each time `a,b and c` are redeclare with new value.so at end of the loop last item value only added with `a,b and c` – prasanth Jan 25 '20 at 06:12
  • 1
    I think maybe you edited your real code too much! I don't see how that can be destructured. Edit your post if I'm right and you want more help, but there's a similar answer here FYI https://stackoverflow.com/questions/47395070/how-to-fix-eslint-error-prefer-destructuring – user2740650 Jan 25 '20 at 06:22
  • @prasanth yes dataArray is like [{}]. And a, b & c are not redeclare because it is declare outside the api calls. It will redeclare when I create this under map function which I not done. Thanks a lot for the interaction – Aks Jan 25 '20 at 06:47
  • @user2740650 yes I write the sudo code here because Actual code is very long. And I don't think actual code Needs here Because I just want to understand the concept. Thanks a lot for the interaction. – Aks Jan 25 '20 at 06:48
  • Please show the actual code, or at least a minimal representation of the actual code - the code, as posted, doesn't make much sense (either in the context of the reassignment of `a` or of the linter warning) – CertainPerformance Jan 25 '20 at 07:01
  • @Aks copy/paste the code you posted above into a new file in the same project. Do you still see the ESLint warning that you posted about? I don't think you will. Provide a small example where ESLint complains for you. – user2740650 Jan 25 '20 at 15:45

2 Answers2

0

It seem like your a, b and c equals the last value of dataArray. So it should be

const { a = '', b = '', c = '' } =
  dataArray.length > 0 ? dataArray[dataArray.length - 1] : {};
invisal
  • 11,075
  • 4
  • 33
  • 54
0

I think in your scenario forEach more suitable than map.

dataArray.forEach(({ valueA, valueB, valueC }) => {
  a = valueA;
  b = valueB;
  c = valueC;
});

Alternatively, if you want to use map, will need to add the inline return statement ({}).

const { a, b, c } = dataArray
  .map(({ valueA: a, valueB: b, valueC: c }) => ({
    a,
    b,
    c
  }))
  .pop() || { a: "", b: "", c: ""};
Siva K V
  • 10,561
  • 2
  • 16
  • 29