更新嵌套对象数组

时间:2019-01-21 21:50:05

标签: javascript arrays object

使用对象数组,我需要更新typeSelect (Multiple Answer)的任何对象的计数。

每个typeSelect (Multiple Answer)的对象包含一个data对象数组,该数组以逗号分隔value,例如“定价过高,独特,高质量”。这些值应分为自己的对象,并包含在该特定count对象数组的新totalcount(所有data值的总和)中。

const arr = [
  {
     data: [
       {count: 7, total: 7, value: "N/A"},
     ],
     name: "item 1",
     type: "Yes/No",
  }, {
     data: [
       {count: 5, total: 7, value: "N/A"},
       {count: 2, total: 7, value: "Yellow"},
     ],
     name: "item 2",
     type: "Select (Single Answer)",
  }, {
     data: [
       {count: 5, total: 7, value: "N/A"},
       {count: 1, total: 7, value: "Overpriced,Unique,High quality"},
       {count: 1, total: 7, value: "Reliable,High quality"},
     ],
     name: "item 3",
     type: "Select (Multiple Answer)",
  },
];

预期结果

const result = [
  {
     data: [
       {count: 7, total: 7, value: "N/A"},
     ],
     name: "item 1",
     type: "Yes/No",
  }, {
     data: [
       {count: 5, total: 7, value: "N/A"},
       {count: 2, total: 7, value: "Yellow"},
     ],
     name: "item 2",
     type: "Select (Single Answer)",
  }, {
     data: [
       {count: 5, total: 10, value: "N/A"},
       {count: 2, total: 10, value: "High quality"},
       {count: 1, total: 10, value: "Overpriced"},
       {count: 1, total: 10, value: "Unique"},
       {count: 1, total: 10, value: "Reliable"},
     ],
     name: "item 3",
     type: "Select (Multiple Answer)",
  },
];

我已经开始使用reduce函数,但是它产生的对象与预期结果相差甚远:

当前代码

arr.reduce((a, c) => {
  a[c.data.value] = a[c.data.value] || { total: 0 };
  a[c.data.value].total += 1;
  return a;
}, {})

不希望的结果

{ undefined: { total: 4 } }

3 个答案:

答案 0 :(得分:3)

您可以收集这些组并获得total,并附上一个结束符。

它具有total上的闭包并返回一个数组

        data: (total => Array.from(


        ))(0)

通过使用MapinitialValue的形式收集数据

             o.data.reduce(


                 new Map
            ),

以及使用counttotalvalue映射新对象的功能。

            ([value, count]) => ({ count, total, value })

reduce的回调中,countvalue被解构并且值被拆分,以将所有计数转换为映射中收集的所有拆分值。同时,total随实际计数增加。最后,返回地图m

                 (m, { count, value }) => (value.split(',').forEach(
                     v => (m.set(v, (m.get(v) || 0) + count), total+= count)
                 ), m),

var data = [{ data: [{ count: 7, total: 7, value: "N/A" }], name: "item 1", type: "Yes/No" }, { data: [{ count: 5, total: 7, value: "N/A" }, { count: 2, total: 7, value: "Yellow" }], name: "item 2", type: "Select (Single Answer)" }, { data: [{ count: 5, total: 7, value: "N/A" }, { count: 1, total: 7, value: "Overpriced,Unique,High quality" }, { count: 1, total: 7, value: "Reliable,High quality" }], name: "item 3", type: "Select (Multiple Answer)" }],
    result = data.map(o => Object.assign({}, o, {
        data: (total => Array.from(
             o.data.reduce(
                 (m, { count, value }) => (value.split(',').forEach(
                     v => (m.set(v, (m.get(v) || 0) + count), total+= count)
                 ), m),
                 new Map
            ),
            ([value, count]) => ({ count, total, value })
        ))(0)
    }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

这是通过一些注释使其清楚的一种方法:

let arr = [{data:[{count:7,total:7,value:"N/A"}],name:"item 1",type:"Yes/No"},{data:[{count:5,total:7,value:"N/A"},{count:2,total:7,value:"Yellow"}],name:"item 2",type:"Select (Single Answer)"},{data:[{count:5,total:7,value:"N/A"},{count:1,total:7,value:"Overpriced,Unique,High quality"},{count:1,total:7,value:"Reliable,High quality"}],name:"item 3",type:"Select (Multiple Answer)"}];

arr.forEach(x => {
  //get all splitted values
  const allValues = x.data.filter(y => y.value.split(',').length > 1).reduce((a, e) => a.concat(e.value.split(',')), []);

  //remove non-splitten values from data array
  x.data = x.data.filter(y => y.value.split(',').length <= 1);

  //create new values from old
  const newData = allValues.reduce((a, y) => {
    const data = a.find(z => z.value === y);
    if (data) {
      data.count++;
      return a;
    };
    return a.concat({ count: 1, value: y });
  }, x.data)
  
  //create new total
  const sumCounters = newData.reduce((a, e) => a + e.count, 0);
  newData.forEach(e => e.total = sumCounters);

  x.data = newData;
  return x;
})

console.log(arr);

答案 2 :(得分:0)

自从我开始从事我的工作以来,已经提供了几个很好的答案,但是我不想浪费我的时间,所以这是我的解决方案。

// OP's original array
const arr = [
  {
     data: [
       {count: 7, total: 7, value: "N/A"},
     ],
     name: "item 1",
     type: "Yes/No",
  }, {
     data: [
       {count: 5, total: 7, value: "N/A"},
       {count: 2, total: 7, value: "Yellow"},
     ],
     name: "item 2",
     type: "Select (Single Answer)",
  }, {
     data: [
       {count: 5, total: 7, value: "N/A"},
       {count: 1, total: 7, value: "Overpriced,Unique,High quality"},
       {count: 1, total: 7, value: "Reliable,High quality"},
     ],
     name: "item 3",
     type: "Select (Multiple Answer)",
  },
];

arr.forEach(function(select){
  // Only modify the multiple answer selects
  if(select.type == 'Select (Multiple Answer)'){
    var newTotal = 0; // calculate a new total as each item is added to the new array
    // use reduce to create a new data array for the multiple answer select
    var newDataArray = select.data.reduce(function(acc,d){
      valueArr = d['value'].split(','); // get a list of separate value strings
      valueArr.forEach(function(valStr){
        var unique = true;
        // if the new array is empty then go ahead and add the first item
        if(acc.length === 0){
          acc.push({'count':d.count,'total':d.total,'value':valStr});
          newTotal += d.count;
        } else {
          // check to see if there is already an object with the same value string
          // if there is then just update the count and set the unique flag so a new element doesn't get added later
          acc.forEach(function(obj){
            if(obj['value'] == valStr){
              obj['count'] += d.count;
              unique = false;
              newTotal += d.count;
            }
          })
          if(unique){
            acc.push({'count':d.count,'total':d.total,'value':valStr});
            newTotal += d.count;
          }      
        }          
      })
      return acc;
    }, []);
    // Update totals
    newDataArray.forEach(function(obj){
      obj.total = newTotal;
    })
    select.data = newDataArray;
  }
})
console.log(arr);