Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     [
       {
        "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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading