使用数组中的公用键对对象进行分组

时间:2019-04-22 05:38:01

标签: javascript arrays object

我有多个具有通用键的对象,正在尝试将所有重复的对象分组并映射任何对象中存在的任何额外键

我的数据如下

var array = [
  { id: 'Staging', cumulative: 16, month: 16, week: 16, yeasterday: 16 },

  { id: 'Staging1', cumulative: 16, yeasterday: 16, week: 16 },
];

预期结果,假设低于

<div class="container">
    <div class='col-md-5'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker6'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <div class='col-md-5'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker7'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        $('#datetimepicker6').datetimepicker();
        $('#datetimepicker7').datetimepicker({
            useCurrent: false //Important! See issue #1075
        });
        $("#datetimepicker6").on("dp.change", function (e) {
            $('#datetimepicker7').data("DateTimePicker").minDate(e.date);
        });
        $("#datetimepicker7").on("dp.change", function (e) {
            $('#datetimepicker6').data("DateTimePicker").maxDate(e.date);
        });
    });
</script>

3 个答案:

答案 0 :(得分:1)

像这样使用reduce

var array = [{
  id: "Staging",
  cumulative: 16
}, {
  id: "Staging",
  yeasterday: 16
}, {
  id: "Staging",
  week: 16
}, {
  id: "Staging",
  yeasterday: 16
}, {
  id: "Staging1",
  cumulative: 16
}, {
  id: "Staging1",
  yeasterday: 16
}, {
  id: "Staging1",
  week: 16
}]

var newArray = array.reduce((acc, { id, ...rest }) => {
  acc[id] = { ...(acc[id] || {}), ...rest };
  return acc;
}, {});

console.log(newArray);

答案 1 :(得分:0)

您可以使用Vanilla JavaScript(无需笨拙的外部库,例如Lodash)来实现此目的。我的方法要求您使用Array.reduce()以及ES6的功能之一Map。然后,我们可以使用spread syntax(或Array.from())将Iterator对象(其中包含Map对象中每个元素的值)转换为数组以获取格式类似于问题中要求的输出。

const arr = [ {id: "Staging", cumulative: 16}, {id: "Staging", yeasterday: 16}, {id: "Staging", week: 16}, {id: "Staging", yeasterday: 16},
{id: "Staging1", cumulative: 16}, {id: "Staging1", yeasterday: 16}, {id: "Staging1", week: 16}
]

const iteratorMap = arr.reduce((entry, e) => entry.set(e['id'], {...entry.get(e['id'])||{}, ...e}), new Map()).values();

const result = [...iteratorMap];

console.log(result);

答案 2 :(得分:0)

您可以轻松使用lodash库并获取结果

var result = _.chain(array)
              .groupBy('id')
              .map((val) => _.reduce(val, (result, value) => _.merge(result, value), {}))
              .value()