简体   繁体   中英

Use function argument inside reduce function : Javascript

I have an array of objects with the following structure that is being sent as response:


    let sampleData = [
      { valueObj: { High: 4, Low: 5,  Medium: 7 } , time: "1571372233234" , sum: 16 },
      { valueObj: { High: 5, Low: 3, Medium : 1 }, time: "1571372233234" , sum: 9},
      { time: "14354545454", sum: 0},
      { time: "14354545454", sum: 0} }
    ];


I need to take each key within each object inside array and form an array out of it. Basically grouping based on the key present in all the objects.If the object has no "values" it should return 0 across the val1,val2,val3.

result = [
  { name: 'High', data: [4, 5, 0, 0] }, 
  { name: 'Medium', data: [5, 3, 0, 0] }, 
  { name: 'Low', data: [7, 1, 0, 0] }
]

Just want to pass an argument to a function, that should be used inside reduce. Here I am passing "valueObj" and that should be used inside reduce. But I am unable to refer the same inside reduce

I have tried the following:

 let sampleData = [{ valueObj: { High: 4, Low: 5, Medium: 7 }, time: "1571372233234", sum: 16 }, { valueObj: { High: 5, Low: 3, Medium : 1 }, time: "1571372233234", sum: 9 }, { time: "14354545454", sum: 0 }, { time: "14354545454", sum: 0 }]; let keys = ['High', 'Low', 'Medium']; function formResult(sampleData, values, keys){ let grouped = sampleData.reduce((r, { values = {} } = {}) => { r.forEach(({ name, data }) => data.push(values[name] || 0)); return r; }, keys.map(name => ({ name, data: [] }))); console.log(grouped); } formResult(sampleData,"valueObj", keys)

Rename the values param (I've used prop ) since it's used in the reduce function. Use destructuring with computed properties to extract the property and assign it to values :

 const sampleData = [{ valueObj: { High: 4, Low: 5, Medium: 7 }, time: "1571372233234", sum: 16 }, { valueObj: { High: 5, Low: 3, Medium : 1 }, time: "1571372233234", sum: 9 }, { time: "14354545454", sum: 0 }, { time: "14354545454", sum: 0 }]; const keys = ['High', 'Low', 'Medium']; function formResult(sampleData, prop, keys){ let grouped = sampleData.reduce((r, { [prop]: values = {} } = {}) => { r.forEach(({ name, data }) => data.push(values[name] || 0)); return r; }, keys.map(name => ({ name, data: [] }))); console.log(grouped); } formResult(sampleData,"valueObj", keys);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM