如何将新数据合并到旧数组?

时间:2018-12-11 08:45:39

标签: javascript jquery

我有一个像这样的数组。在这里,我仅包含5个字段,但实际上我大约有45个字段名。

0: {id:1, product_name: 'aaa', val1:1, val2:2, val3:4}
1: {id:2, product_name: 'bbb', val1:1, val2:2, val3:4}
2: {id:3, product_name: 'ccc', val1:1, val2:2, val3:4}
3: {id:4, product_name: 'ddd', val1:1, val2:2, val3:4}

我想获取val1,val2和val3的总和并显示在总计列中,并将'%'符号也附加到这3个值上。

我做了以下操作以获取总和并附加%

temp = temp.map((row) => {
    const newRow= {};
    let total = 0;

    total = row['val1'] +
            row['val2'] +
            row['val3'] +

    newRow['total'] = total;

    newRow['val1'] = row['val1'] + '%';
    newRow['val2'] = row['val2'] + '%';
    newRow['val3']   = row['val3'] + '%';

    return newRow;
});

使用此代码,我仅在数组中返回val1,val2和val3。如何附加其他42列并得到最终结果。

3 个答案:

答案 0 :(得分:1)

您可以获取所需键的数组并为单个数组映射新属性。

var data = [{ id: 1, product_name: 'aaa', val1: 1, val2: 2, val3: 4 }, { id: 2, product_name: 'bbb', val1: 1, val2: 2, val3: 4 }, { id: 3, product_name: 'ccc', val1: 1, val2: 2, val3: 4 }, { id: 4, product_name: 'ddd', val1: 1, val2: 2, val3: 4 }],
    keys = ['val1', 'val2', 'val3'],
    result = data.map(o => Object.assign(...keys.map(
        (t => k => ({ total: t += o[k], [k]: o[k] + '%' }))
        (0)
    )));

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

为物体休息。

var data = [{ id: 1, product_name: 'aaa', val1: 1, val2: 2, val3: 4 }, { id: 2, product_name: 'bbb', val1: 1, val2: 2, val3: 4 }, { id: 3, product_name: 'ccc', val1: 1, val2: 2, val3: 4 }, { id: 4, product_name: 'ddd', val1: 1, val2: 2, val3: 4 }],
    result = data.map(({ id, product_name, ...o, total = 0 }) => Object.assign(
        { id, product_name },
        ...Object.entries(o).map(([k, v]) => (total += v, { [k]: v + '%' })),
        { total }
    ));

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

答案 1 :(得分:1)

你可以那样做

var temp = [{id:1, product_name: 'aaa', val1:1, val2:2, val3:4},
{id:2, product_name: 'bbb', val1:1, val2:2, val3:4},
{id:3, product_name: 'ccc', val1:1, val2:2, val3:4},
{id:4, product_name: 'ddd', val1:1, val2:2, val3:4}];

temp = temp.map(row => {
  const newRow = row;
  let total = 0;

  total = parseInt(row['val1']) +
    parseInt(row['val2']) +
    parseInt(row['val3']);

  newRow['total'] = total;

  newRow['val1'] = row['val1'] + '%';
  newRow['val2'] = row['val2'] + '%';
  newRow['val3'] = row['val3'] + '%';

  return newRow;
});
$("#result").append(JSON.stringify(temp) + "<br />");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='result'>

</div>

答案 2 :(得分:0)

您需要将const newRow的定义更改为:

let temp = this.some.map((row) => {
  const newRow = {...row};
  let total = 0;
  total = row['val1'] +
          row['val2'] +
          row['val3'];
  newRow['total'] = total;

  newRow['val1'] = row['val1'] + '%';
  newRow['val2'] = row['val2'] + '%';
  newRow['val3'] = row['val3'] + '%';

  return newRow;
});