我有一个具有重复值的对象,我需要获取重复值并将其插入父对象中

时间:2018-11-05 00:44:55

标签: javascript arrays json

.done(function(data){
    var items = data.d.results;
    var programas = new Object();
    var titleProgramaId = "";
    var titleProgramaIdAtual = "";
    for ( var i = 0; i < items.length; i++) {
        titleProgramaIdAtual = items[i].Concessao.Title+"-"+items[i].ConcessaoId;           
        if(titleProgramaIdAtual != titleProgramaId){
            programas[i] = {"Title":items[i].Concessao.Title,"Ano":items[i].Concessao.AnoPrograma,"Id":items[i].ConcessaoId};
            titleProgramaId = titleProgramaIdAtual;
        }
    }
    console.log(programas);
    console.log(items);



 {0: {…}, 4: {…}, 5: {…}, 7: {…}, 8: {…}, 9: {…}}
0: {Title: "Programa 1", Ano: "2015", Id: 3}
4: {Title: "Programa 2", Ano: "2015", Id: 8}
5: {Title: "Programa 2", Ano: "2016", Id: 4}
7: {Title: "Programa 3", Ano: "2017", Id: 5}
8: {Title: "Programa 1", Ano: "2018", Id: 9}
9: {Title: "Programa 4", Ano: "2018", Id: 6}

我需要从ID对象获取重复值并在其中创建一个新的对象数组。有人帮我吗?

1 个答案:

答案 0 :(得分:0)

此功能将按 Id

分组
 getDuplicatedArray(inputArray) {
    var result= inputArray.reduce(function (acc, item) {
      let key = (item['Id']);
      (acc[key] ? acc[key] : (acc[key] = null || [])).push(item);
      return acc;
    }, {});
    return result
  }

示例演示

https://stackblitz.com/edit/js-reduce-duplicate?file=index.js