推送到数组中的多维对象

时间:2018-06-09 20:44:38

标签: javascript arrays object

我有2个数组,我想为每个商店创建一个多维数组。 结果,“水果”和“蔬菜”的值不是每个的总和,结果是总分(每个水果或蔬菜的总和*每个的得分)

var myArray = [{
                shop: "shop1",
                item1: "my apple 0",
                item2: "my carrot 1",
            }, {
                shop: "shop1",
                item1: "my apple 0",
                item2: "my carrot 1",
            }, {
                shop: "shop1",
                item1: "my apple 1",
                item2: "my carrot 0",
            },
            {
                shop: "shop2",
                item1: "my apple 1",
                item2: "my carrot 1",
            }, {
                shop: "shop2",
                item1: "my apple 1",
                item2: "my carrot 0",
            }, {
                shop: "shop2",
                item1: "my apple 0",
                item2: "my carrot 1",
            }
        ];

        var MyArrayDefinition = [{
                item: "my apple 0",
                color: "red",
                group: "fruit",
                score: 0
            }, {
                item: "my carrot 1",
                color: "orange",
                group: "vegetable",
                score: 1
            },
            {
                item: "my apple 1",
                color: "red",
                group: "fruit",
                score: 1
            }, {
                item: "my carrot 0",
                color: "orange",
                group: "vegetable",
                score: 0
            }
        ]

这是我的功能

const count = myArray
            .reduce((a, o) => a.concat(Object.values(o)), [])
            .reduce((c, v) => ({ ...c,
                [v]: (c[v] || 0) + 1
            }), {});

        const list = Object.entries(count)
            // map to {type, count}
            .map(([item, number]) => ({
                item,
                number
            }));

        const indices = MyArrayDefinition.map((e) => e.item);
        const combinaison = list.map(e => Object.assign(e, MyArrayDefinition[indices.indexOf(e.item)]));

        var result = _.map(combinaison, function(elt) {
            return ({
                item: elt.question,
                group: elt.group,
                color: elt.color,
                score: Number(elt.score),
                number: elt.number,
                totalPoints: elt.number * Number(elt.score)
            });
        });


        var resultArray = {};
        for (var i = 0; i < result.length; i++) {
            if (!resultArray.hasOwnProperty(result[i].group)) {
                resultArray[result[i].group] = 0;
            }
            resultArray[result[i].group] += result[i].totalPoints;
        };
        delete resultArray.undefined;

我想要一个这样的结果:在每个对象“shop”中创建一个对象

var resultArray = [{
                id: 1,
                shop: 'shop1',
                itemGroup: {
                    fruit: 1,
                    vegetable: 2
                }
            },
            {
                id: 2,
                shop: 'shop2',
                itemGroup: {
                    fruit: 2,
                    vegetable: 2
                }
            }
        ]

我试试这个

var out = _(groupByShop).map(function(g, key) {
            return {
                shop: key,
                item: _(g).reduce((a, o) => a.concat(Object.values(o)), []).reduce((c, v) => ({ ...c,
                    [v]: (c[v] || 0) + 1
                }), {}),
                groupOfItems: Object.entries(_(g).reduce((a, o) => a.concat(Object.values(o)), []).reduce((c, v) => ({ ...c,
                    [v]: (c[v] || 0) + 1
                }), {})).map(([item, total]) => ({
                    item,
                    total
                }))
    };
        });

2 个答案:

答案 0 :(得分:0)

如果你想要每个商店的总和独特成果,我不确定你想要的输出是否正确,因为你的例子结果似乎是错误的。

您可以尝试以下操作,看看它是否符合您的目的,控制台记录其他一些变量(在此处记录会使其过长)。

const myArray = [{"shop":"shop1","item1":"my apple 0","item2":"my carrot 1"},{"shop":"shop1","item1":"my apple 0","item2":"my carrot 1"},{"shop":"shop1","item1":"my apple 1","item2":"my carrot 0"},{"shop":"shop2","item1":"my apple 1","item2":"my carrot 1"},{"shop":"shop2","item1":"my apple 1","item2":"my carrot 0"},{"shop":"shop2","item1":"my apple 0","item2":"my carrot 1"}];

const MyArrayDefinition = [{"item":"my apple 0","color":"red","group":"fruit","score":0},{"item":"my carrot 1","color":"orange","group":"vegetable","score":1},{"item":"my apple 1","color":"red","group":"fruit","score":1},{"item":"my carrot 0","color":"orange","group":"vegetable","score":0}];

const shopArticle = myArray.reduce(
  (result,record)=>{
    result[record.shop]=result[record.shop] || [];
    result[record.shop] = result[record.shop].concat(
      Object.keys(record).filter(key=>key.startsWith("item")).reduce(
        (r,key)=>r.concat(record[key]),
        []
      ),
      []
    );
    return result;
  },
  {}
);
const groups = MyArrayDefinition.reduce(
  (result,{item,group,score})=>{
    result[item] = {group,score};
    return result;
  },
  {}
)
console.log(
  Object.keys(shopArticle)
  .sort((a,b)=>a.localeCompare(b))
  .map(
    (key,id)=>({id:id+1,shop:key,itemGroup:shopArticle[key].reduce(
      (result,key)=>{
        result[groups[key].group] += groups[key].score;
        return result;
      },
      {fruit:0,vegetable:0}
    )})
  )
)

答案 1 :(得分:0)

我不太确定我是否理解乘法部分,但似乎与结果相符:

var myArray = [ { shop1: "shop1", item1: "my apple 0", itemA: "my carrot 1" }, 
                { shop2: "shop1", item2: "my apple 0", itemB: "my carrot 1" }, 
                { shop3: "shop1", item3: "my apple 1", itemC: "my carrot 0" },
                { shop4: "shop2", item4: "my apple 1", itemD: "my carrot 1" }, 
                { shop5: "shop2", item5: "my apple 1", itemE: "my carrot 0" }, 
                { shop6: "shop2", item6: "my apple 0", itemF: "my carrot 1" } ];

var MyArrayDefinition = [ 
  { item: "my apple 0" , color: "red"   , group: "fruit"    , score: 0 }, 
  { item: "my carrot 1", color: "orange", group: "vegetable", score: 1 }, 
  { item: "my apple 1" , color: "red"   , group: "fruit"    , score: 1 }, 
  { item: "my carrot 0", color: "orange", group: "vegetable", score: 0 } ];

var k = Object.keys, items = MyArrayDefinition.reduce((o, v) => (o[v.item] = v, o), {}); 

var shops = myArray.reduce((o, v, i, s) => (
  s = v[k(v).find(k => k.includes('shop'))], 
  s = o[s] || (o[s] = { fruit: 0, vegetable: 0 }), 
  k(v).forEach(k => k.includes('item') && 
    (s[(i = items[v[k]]).group] += i.score) ), o), {}); 

var result = k(shops).map((k, i) => ({ id: i + 1, shop: k, itemGroup: shops[k] })); 

console.log( JSON.stringify( shops  ).replace(/},/g, '},\n ') );
console.log( JSON.stringify( result ).replace(/},/g, '},\n ') );