Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have array and I want to merge duplicated items.

var arr = [{
    'id': 1,
    'text': 'ab'
}, {
    'id': 1,
    'text': 'cd'
}, {
    'id': 2,
    'text': 'other'
}, {
    'id': 3,
    'text': 'afafas'
}, {
    'id': 4,
    'text': 'asfasfa'
}];

var work = arr.reduce(function(p, c) {
    var key = c.id;

    p[key].text.push(c.text);
});

console.log(work);

And output must be like that:

[{
    'id': 1,
    'text': ["[ab] [cd]"]
}, {
    'id': 2,
    'text': 'other'
}, {
    'id': 3,
    'text': 'afafas'
}, {
    'id': 4,
    'text': 'asfasfa'
}]

Here is what I tried but result is fail: ( https://jsfiddle.net/2m7kzkba/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you're not averse to using a utility library like Underscore, something like this will work:

function mergeListOfObjects(arr) {
  function objectID(obj) {
    return obj.id;
  }

  function objectText(obj) {
    return obj.text;
  }

  function mergeObject(id) {
    return {id: id, text: _.map(_.where(arr, {id: id}), objectText) }; 
  }

  return _.map(_.uniq(_.map(arr, objectID)), mergeObject);
}

console.log(mergeListOfObjects(arr));

n.b. This doesn't account for the fact that your example output added some extra brackets out of nowhere, i.e., 'text': ["[ab]", "[cd]"]. I think the output you wanted is more like 'text': ["ab", "cd"].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...