-1

Is there any way i can filter values which are present inside Object

[
{
id: "1",
name:"animal_image.jpg"
},
{
id: "2",
name:"fish_image.jpg"
},
{
id: "3",
name:"animal_doc.txt"
},{
id: "4",
name:"fish_doc.txt"
},
{
id: "4",
name:"flower_petals.jpg"
},
{
id: "5",
name:"plant_roots.jpg"
},
{
id: "6",
name:"human_image.jpg"
},
]

i want to filter all the name which contain_image.jpg so output look like this

output= 
[ "human_image.jpg",
  "anima_image.jpg",
  "fish_image.jpg"
]
Aakash
  • 139
  • 1
  • 3
  • 22
  • 1
    Please add the code you've tried. A loop and check on the `name` property should work. – adiga May 25 '21 at 09:41
  • Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – evolutionxbox May 25 '21 at 09:42

2 Answers2

2

filter & map

const output = arr
  .filter(x => x.name.endsWith('_image.jpg'))
  .map(x => x.name);
James
  • 80,725
  • 18
  • 167
  • 237
2

In this code snippet filtredData is an array of objects where the name includes _image.jpg and output is just an array of names containing _image.jpg

const data = [
    {
        id: "1",
        name: "animal_image.jpg"
    },
    {
        id: "2",
        name: "fish_image.jpg"
    },
    {
        id: "3",
        name: "animal_doc.txt"
    }, {
        id: "4",
        name: "fish_doc.txt"
    },
    {
        id: "4",
        name: "flower_petals.jpg"
    },
    {
        id: "5",
        name: "plant_roots.jpg"
    },
    {
        id: "6",
        name: "human_image.jpg"
    },
]

const filtredData = data.filter(el => el.name.includes("_image.jpg"));

console.log(filtredData);

const output = filtredData.map(el => el.name);

console.log(output);
Mohamed Oraby
  • 916
  • 3
  • 8
  • 14
  • hey @Mohamed if i also want plant_roots.jpeg and flower_petals.jpg but in another array how can i get it ? – Aakash May 25 '21 at 11:00
  • You want all names that doesn't end with `_image.jpg` or `_doc.txt` right? `const filtredData2 = data.filter(el => !(el.name.includes("_image.jpg") || el.name.includes("doc.txt")));` and `const output2 = filtredData2.map(el => el.name);` – Mohamed Oraby May 25 '21 at 11:05
  • hey sorry @mohammed to disturb you but i only want to filter files whos extension end with `.jpg` what if there are `.pdf .txt .mp4` extension and i want to filter `.jpg` and then again filter `_image.jpg` and rest `.jpg` file in other array. i hope you have solution for that – Aakash May 25 '21 at 11:24
  • You can edit the `includes('')` part to specify what you want or use `endsWith(''.ext)`, What I mean is that you can use the same syntax and just change the condition – Mohamed Oraby May 25 '21 at 11:27