2

have a feeling I am missing something obvious here. I was using a reduce function like so

const obj = this.data.reduce((ac,{Category, Count}) => (ac[Category] = Count,ac),{});

However, I now need Category and Count to be dynamic, using a variable. As such, I have done

const cat = this.format.header[0];
const count = this.format.header[1];
const obj = this.data.reduce((ac,{cat, count}) => (ac[cat] = count,ac),{});

This does not seem to be using my variables though. I have also tried using this within it, but this also does not work.

How can I use these variables within the reduce?

Thanks

5
  • 1
    do you have some data and the wanted result? Commented Jun 8, 2019 at 16:22
  • 1
    It's not 100% clear what you're asking, but you can't do that with destructuring. You'll have to extract the properties explicitly. Commented Jun 8, 2019 at 16:22
  • What is this and this.data? Also, why don't you just use an arrow function with curly braces then define your variables inside of that? Commented Jun 8, 2019 at 16:23
  • sorry, this.data is an array. This is a component in VueJS, I am passing stuff via props Commented Jun 8, 2019 at 16:25
  • You can't destructure those variables but you can pass them as a key to your object Commented Jun 8, 2019 at 16:32

2 Answers 2

4

You can't use destructuring this way to approach what you want:

this.data.reduce((ac,{cat, count}) => (ac[cat] = count,ac),{});

That will try to access properties cat and count from the objects that belongs to the array, not the ones that holds your variables. However, you can do like this:

const cat = this.format.header[0];
const count = this.format.header[1];
const obj = this.data.reduce((ac, o) => (ac[o[cat]] = o[count], ac), {});
Sign up to request clarification or add additional context in comments.

Comments

3

The cat and count variables inside the reduce() call back will refer to the properties cat and count on each object is array of objects this.data.

If you want to destrucutre the properties using variables. Then use following syntax

[propName]:newName

Here is your code.

const cat = this.format.header[0];
const count = this.format.header[1];
const obj = this.data.reduce((ac,{[cat]:cat, [count]:count}) => (ac[cat] = count,ac),{});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.