Search code examples
javascriptarraysmapsjavascript-objects

JavaScript array and object mapping


I have two javascript variables

1 an array called categories:

["Casual & Fashion", "Jackets", "PPE & Safety Equipment", "Sports & Leisure", "Workwear", "Accessories"]

2 an array of objects called result:

  [
    {field: "Workwear", cost: 1.3, cost_p2: 0, cost_diff: -1.3, revenue: 2.6},
    {field: "Hide", cost: 2.8, cost_p2: 0, cost_diff: -2.8, revenue: 5.6},
    {field: "Accessories", cost: 0, cost_p2: 3.1, cost_diff: 3.1, revenue: 10},
    {field: "Safety boots", cost: 24.95, cost_p2: 0, cost_diff: -24.95, revenue: 91},
    {field: "Safety Shoes", cost: 13.9, cost_p2: 0, cost_diff: -13.9, revenue: 27.8},
    {field: "Shorts", cost: 7.45, cost_p2: 0, cost_diff: -7.45, revenue: 14.9},
    {field: "Soft Shell", cost: 17.3, cost_p2: 17.3, cost_diff: 0, revenue: 31.92}
  ]

Now, as you see, "workwear" and "accessories" appear in both so I need my final array to look like this (based on the original categories):

[
    {"Casual & Fashion": 0}, 
    {"Jackets": 0}, 
    {"PPE & Safety Equipment": 0}, 
    {"Sports & Leisure": 0}, 
    {"Workwear": 2.6}, 
    {"Accessories": 10}
  ]

taking just the matching "field" values and related "revenue" values

I can verbalise the logic but the syntax is stretching my capability.

Any help appreciated. Thanks


Solution

  • Yes, there are 2 loops, map and find:

    const categories = ["A", "B", "C", "D"];
    const result = [{"A" : 3}, {"D" : 7}];
    
    const final = categories.map(category => {
      const resultItem = result.find(item => category in item);
      return resultItem ?? { [category]: 0 };
    });
    
    console.log(final);
    // [
    //  0: { A: 3 },
    //  1: { B: 0 },
    //  2: { C: 0 },
    //  3: { D: 7 }
    // ]
    

    Answer, after original question wording changed:

    const final = categories.map(category => {
      const resultItem = result.find(item => item.field === category);
      return { [category]: resultItem ? resultItem.revenue : 0 };
    });
    
    console.log(final);
    // [
    //  0: {Casual & Fashion: 0},
    //  1: {Jackets: 0},
    //  2: {PPE & Safety Equipment: 0},
    //  3: {Sports & Leisure: 0},
    //  4: {Workwear: 2.6},
    //  5: {Accessories: 10}
    // ]
    

    And this code is tested too.