Lodash create collection from duplicate object keys

前端 未结 3 1029
轻奢々
轻奢々 2020-12-04 00:35

I have the following structure:

var output = [{
    \"article\": \"BlahBlah\",
    \"title\": \"Another blah\"
}, {
    \"article\": \"BlahBlah\",
    \"titl         


        
3条回答
  •  抹茶落季
    2020-12-04 00:50

    A proposal in plain Javascript

    It uses a IIFE (Immediate Invoked Function Expression) for using private variables and for collecting the return values in an array.

    Beside that it uses a hash table for the reference to the right array item.

    var output = [{ article: "BlahBlah", title: "Another blah" }, { article: "BlahBlah", title: "Return of the blah" }, { article: "BlahBlah2", title: "The blah strikes back" }, { article: "BlahBlah2", title: "The blahfather" }],
        newOutput = function (data) {
            var r = [];
            data.forEach(function (a) {
                if (!this[a.article]) {
                    this[a.article] = { article: a.article, titles: [] };
                    r.push(this[a.article]);
                }
                this[a.article].titles.push(a.title);
            }, Object.create(null));
            return r;
        }(output);
            
    console.log(newOutput);

提交回复
热议问题