-2

I want to write a method that returns the name field of the person whose color id I entered. How do I do this? For example, when I type 97, the name "Veli" will give to me.

const data = [
    {
        id: 1,
        name: "Ali",
        colorList: [
            {
                id: 99,
                color_name: 'yellow',
            }
        ],     
    },
    {
        id: 2,
        name: "Veli",
        colorList: [
            {
                id: 98,
                color_name: 'red',
            },
            {
                id: 97,
                color_name: 'blue',
            },
        ]
    }
]
Layhout
  • 1,445
  • 1
  • 3
  • 16
oguzcan
  • 57
  • 6

2 Answers2

0

You can do it by using .filter() and .some()

const arr = [{ id: 1, name: "Ali", colorList: [{ id: 99, color_name: 'yellow', }], }, { id: 2, name: "Veli", colorList: [{ id: 98, color_name: 'red', }, { id: 97, color_name: 'blue', }, ] } ];
const find = (target)=>arr.filter(({name, colorList:cl})=>cl.some(o=>o.id === target)).map(it=>it.name);
console.log(find(97));
Asraf
  • 1,322
  • 2
  • 12
0

We can use Array.find() and Array.some() to do it

let data =   [{
              id: 1,
              name: "Ali",
              colorList: [
                {
                  id: 99,
                  color_name: 'yellow',
                }
              ],
              
            },
            {
              id: 2,
              name: "Veli",
              colorList: [
                {
                  id: 98,
                  color_name: 'red',
                },
                {
                  id: 97,
                  color_name: 'blue',
                },
              ]
            }]
            
const filterData = (value,param) => {
  return value.find(v1 => v1.colorList.some(v2 => v2.id === param)).name
}           
            
console.log(filterData(data,97))
flyingfox
  • 13,414
  • 3
  • 24
  • 39