Search code examples
javascriptarraysjavascript-objects

Compare Array of Objects in Javascript


I'd like to make this array:

[
   {main: "material", value: "blend"}, 
   {main: "material", value: "synthetic"}, 
   {main: "style", value: "curl"}, 
   {main: "style", value: "bob"}, 
   {main: "material", value: "premium"}
]

to this:

{
 material: ["blend", "synthetic", "premium"], 
 style: ["curl", "bob"]
}

I used two "for-loops" but it didn't work out well:( Quite newbie in Javascript🥲


Solution

  • You can use reduce to have that result

    const data = [{
      main: "material",
      value: "blend"
    }, {
      main: "material",
      value: "synthetic"
    }, {
      main: "style",
      value: "curl"
    }, {
      main: "style",
      value: "bob"
    }, {
      main: "material",
      value: "premium"
    }]
    
    const finalResut = data.reduce((result, currentData) => {
      const {
        main,
        value
      } = currentData
      if (!result[main]) {
        result[main] = []
      }
      result[main].push(value)
      return result
    }, {})
    
    console.log(finalResut)
    .as-console-wrapper {
      max-height: 100% !important;
      top: 0;
    }