Home > Enterprise >  How to get objects by searching the array content
How to get objects by searching the array content

Time:12-24

I have this object

let obj = [
   {name: 'title 1', values:['test 1', 'test 2']},
   {name: 'title 2' values: ['test 3', 'test 4']}
]

I want to search for values = 'test 3' and it will return objects contaning that skills ouput: {name: 'title 2' values: ['test 3', 'test 4']}

I have tried searching like obj.find(c=> c.skills), iteration etc. but it only works not inside the array of objects.

CodePudding user response:

I'd use filer to apply a condition on values:

 let obj = [
   {name: 'title 1', values:['test 1', 'test 2']},
   {name: 'title 2', values: ['test 3', 'test 4']}
];

const result = obj.filter(o => o.values.includes('test 3'));

console.log(result);

CodePudding user response:

You could find the object by looking into the array with Array#includes.

const
    objects = [{ name: 'title 1', values: ['test 1', 'test 2'] }, { name: 'title 2', values: ['test 3', 'test 4'] }],
    value = 'test 3',
    result = objects.find(({ values }) => values.includes(value));

console.log(result);

CodePudding user response:

Use filter:

let obj = [{
  name: 'title 1',
  values: ['test 1', 'test 2']
}, {
  name: 'title 2',
  values: ['test 3', 'test 4']
}];

let skill = 'test 3';
let result = obj.filter(c => c.values.includes(skill));

console.log(result);

CodePudding user response:

filter() and indexOf() should do it.

let obj = [
   {name: 'title 1', values:['test 1', 'test 2']},
   {name: 'title 2', values: ['test 3', 'test 4']}
];
    
    let ans = obj.filter(x => x.values.indexOf('test 3') > -1);
    console.log(ans);

CodePudding user response:

filter with includes already done. find with includes already done. Then i show the forEach version today ;-)

obj = [{
  name: 'title 1',
  values: ['test 1', 'test 2']
}, {
  name: 'title 2',
  values: ['test 3', 'test 4']
}];

n = []
obj.forEach(c => {
  if (c.values.includes('test 3')) {
    n.push(c)
  }
})

console.log('new', n)

  • Related