将公共对象附加到一个数组中并删除重复项

时间:2017-12-23 11:53:39

标签: javascript lodash

我正在尝试从Javascript数组中删除重复的对象。

我有一个这样的对象

var actualObj = [
  {
    "name": "Sam",
    "id": "1",
    "dept": "Inventory",
    "info": {
      "key1": "test1",
      "key2": "test2",
      "key3": "test3"
    }
  },
  {
    "name": "Paul",
    "id": "2",
    "dept": "Inventory",
    "info": {
      "key1": "test1",
      "key2": "test2",
      "key3": "test3"
    }
  },
  {
    "name": "Sam",
    "id": "1",
    "dept": "Inventory",
    "info": {
      "key4": "test4",
      "key5": "test5",
      "key6": "test6"
    }
  }
]

我试图删除重复项并合并" info"进入对象数组,就像这样

var expectedObj = [
  {
    "name": "Sam",
    "id": "1",
    "dept": "Inventory",
    "info": [
      {
        "key1": "test1",
        "key2": "test2",
        "key3": "test3"
      },
      {
        "key4": "test4",
        "key5": "test5",
        "key6": "test6"
      }
    ]
  },
  {
    "name": "Paul",
    "id": "2",
    "dept": "Inventory",
    "info": {
      "key1": "test1",
      "key2": "test2",
      "key3": "test3"
    }
  }
]

在" info"中使用相同的值对象,我尝试使用Lodash,效果很好JSFIDDLE

任何人都可以帮助我从实际对象中实现预期的对象。我试图通过Combining创建期望的对象作为一个具有相似id值的对象。

2 个答案:

答案 0 :(得分:1)

你可以试试这个,希望它对你有用。

for(let i = 0; i < actualObj.length; i++) {
    let o = actualObj[i];
    for(let j = i+1; j < actualObj.length; j++) {
        let b = actualObj[j];
        // dublicate object identified by id
        if (o.id === b.id) {
            const info = [];
            info.push(o.info);
            info.push(b.info);
            o.info = info;
            actualObj.splice(j, 1); 
        }
    }
}

如果您的重复对象被其他属性(例如name和dept)识别,那么只需更新if条件,如

if (o.id === b.id && o.name === b.name && o.dept === b.dept)

答案 1 :(得分:1)

使用lodash,_.groupBy()项目id,然后_.map()将这些组转换为请求的格式,使用_.omit()获取没有信息的基础对象,以及{ {1}}获取_.map()数组。使用_.assign()

组合到单个对象

info
var actualObj = [{"name":"Sam","id":"1","dept":"Inventory","info":{"key1":"test1","key2":"test2","key3":"test3"}},{"name":"Paul","id":"2","dept":"Inventory","info":{"key1":"test1","key2":"test2","key3":"test3"}},{"name":"Sam","id":"1","dept":"Inventory","info":{"key4":"test4","key5":"test5","key6":"test6"}}];

var result = _(actualObj)
  .groupBy('id')
  .map(function(group) {
    return _.assign(_.omit(group[0], 'info'), {
      info: _.map(group, 'info')
    });
  })
  .value();
  
console.log(result);