Search code examples
javascriptarraysobject

Get objects in array on property and with specific value of key


I need to find all objects of array, which contain color "green" in "mode" property.

let arr = [
  {
    "type": "One",
    "mode": [{ 
        "color": "blue", 
        "size": "L"
      }
    ]
  }, {
    "type": "Two",
    "mode": [{ 
        "color": "green", 
        "size": "M"
      }
    ]
  },{
    "type": "Three",
    "mode": [{ 
        "color": "green", 
        "size": "L"
      }
    ]
  },{
    "type": "Four",
    "mode": [{ 
        "color": "red", 
        "size": "XS" 
      }
    ]
  }
];
    
    
let result = arr.indexOf(arr.find(function(el,index){
  return el['mode'][0].color === 'green';
}))

console.log(result);

Currently I can only get the index.

I would like to get something like this in the output:

     [
       {
        "type": "Two",
        "mode": [{ 
            "color": "green", 
            "size": "M"
          }
        ]
      },{
        "type": "Three",
        "mode": [{ 
            "color": "green", 
            "size": "L"
          }
        ]
      }
    ]

Solution

  • Use Array.prototype.filter and Array.prototype.some to search the inner array

    const filterByModeColor = (arr, color) =>
      arr.filter(ob => ob.mode?.some(o => o.color == color));
    
    const myArr = [
      {"type": "One", "mode": [{"color": "blue", "size": "L"}]},
      {"type": "Two", "mode": [{"color": "green", "size": "M"}]},
      {"type": "Three", "mode": [{"color": "green", "size": "L"}]},
      {"type": "Four", "mode": [{"color": "red", "size": "XS"}]}
    ];
    
    const filtered = filterByModeColor(myArr, "green");
    console.log(filtered);

    To additionally filter the inner "mode": arrays use Array.prototype.reduce instead.

    const filterByModeColor = (arr, color) => arr.reduce((acc, obj) => {
      const mode = obj.mode.filter(o => o.color === color);
      mode.length && acc.push({...obj, mode});
      return acc;
    }, []);
    
    const myArr = [
      {"type": "One", "mode": [{"color": "blue", "size": "L"}, {"color": "green", "size": "L"}]},
      {"type": "Two", "mode": [{"color": "green", "size": "S"}, {"color": "green", "size": "M"}, {"color": "red", "size": "Xl"}]},
      {"type": "Three", "mode": [{"color": "yellow", "size": "L"}, {"color": "blue", "size": "XL"}]},
      {"type": "Four", "mode": [{"color": "red", "size": "XS"}]}
    ];
    
    const filtered = filterByModeColor(myArr, "green");
    console.log(filtered);